<?php 
/**
 * Products controller is one of the most important controller 
 * 
 * @author Norman
 *
 */
class ProductsController extends Zend_Controller_Action
{
	
	protected static $arrShopMaping; 
	
	protected  static $arrbarCodeFilter = array("INSTALL","INSTALLATION","PHONEREPAIR","CN","SERVICE","INSTALL","PARTSSALES","OFF-DUTY-OFFLINE","ON-DUTY-OFFLINE","FAULTY","VOUCHER","STRAP-");
	//$bcFilter = array("INSTALL","INSTALLATION","STRAP-","DELITEM","STA-","FAULTY","VOUCHER","PHONEREPAIR");
	
	
    public function init(){
    /**
	 *
	 *
	 */    
	self::$arrShopMaping = unserialize(ARR_APOS_NEW_SHOP_MAPPING);
		}

	/**
	 * Entry page of products
	 */	
    public function indexAction(){
	
		//echo "Watch Dog Controller";	    
		}
		
	/**
	 * This is the first step that generator weekly order 
	 * this page only have the landing links of generate function 
	 * print out function and verify function is in the second page 
	 * when generate , it clears all the order 
	 */
	public function salesLastWeekMainGeneratorAction(){
			$weekOrder = new Model_DbTable_Order_Weeklyorder();
			$shopList = unserialize(ARR_SHOP_ACTIVE);
			$sp = $this->_getParam("sp");
			$orderCheck = array();
			foreach ($shopList as $k => $v){
				$preFix = "PD";
				$datePD = Model_DatetimeHelper::getThisWeekMonday("");
				
				$noOrder = $preFix.$v.$datePD;
			
				$check = $weekOrder->getOrderByNo($noOrder);
				
				if($check){
					$orderCheck[$v] = 'yes';
				}else{
					$orderCheck[$v] = 'no';
				}
			}
			$this->view->orderCheck = $orderCheck;
			if($sp == "sp"){
				$this->view->sp = $sp;
			}else{
				$this->view->sp = 'no';
			}

			if(isset($_POST['submit'])){
				$i = 0;
				foreach ($shopList as $k2 => $v2){
					echo $v2."  Time:".Model_DatetimeHelper::timeNow()."<br/>";
					$i++;
					if($i%4 == 0){
						sleep(5);
					}
					$url = "http://".SERVER_IP_COMM."/products/generate-weeks-order/shop/".$v2."/gen/yes";
					$this->_redirect($url);
					
				}
	
			}
			
			
		}

		
	/**
	 * For check case List of WH qty > 3 && Shop qty = 0 without order
	 */	
		
	public function stockZeroCheckAction(){
		$shop = $this->_getParam("shop");
		
		$invPro = Model_Aposinitnew::initAposInvPro($shop);
		$stockWh = Model_Aposinitnew::initProBalanceAll();
		$stockShop = Model_Aposinitnew::initProStock($shop);
		$pd = Model_Aposinitnew::initProDes();
		$weeklyOrder = new Model_DbTable_Order_Weeklyorder(Zend_Registry::get('db_remoteapp'));
		$orderCate = new Model_Products_Categoryorder(Zend_Registry::get('db_remoteapp'));
		$pro = new Model_DbTable_Productsva(Zend_Registry::get('db_remoteapp'));
		$thisMonday = Model_DatetimeHelper::getThisWeekMonday("");
		$noOrder = "PD".$shop.$thisMonday;
		
		$cList = $stockWh->listStockWhHave();
		$sList = $stockShop->listShopEmpty($shop);
		$oList = $weeklyOrder->getOrderByNo($noOrder);
	
		
		$whList = array();
		foreach ($cList as $k => $v){
			$sCode = trim($v['SCODE']);
			if(!in_array($sCode,self::$arrbarCodeFilter) && strpos($sCode,"STRAP-") === false){
				$whList[$sCode] = (int)$v['BALANCE'];
			}
		}
		
		
		$sNoStock = array(); 	//Shop no stock item
		foreach ($sList as $k2 => $v2){	
			$sCode = trim($v2['SCODE']);
			if(!in_array($sCode,self::$arrbarCodeFilter) && strpos($sCode,"STRAP-") === false){
				$sNoStock[$sCode] = 0;
			}
		}
		$shopOrder = array(); 	//Shop order qty > 0 list
		foreach ($oList as $k3 => $v3){
			if($v3['qty_order_shop'] > 0){
				$shopOrder[$v3['code_product']] = $v3['qty_order_shop'];
			}
			
		}

		$list = array();
		foreach ($cList as $k => $v){	
			$sCode = trim($v['SCODE']);
			if(!in_array($sCode,self::$arrbarCodeFilter) && strpos($sCode,"STRAP-") === false){
				if((int)$v['BALANCE'] < 20 && array_key_exists($sCode, $sNoStock) && !array_key_exists($sCode, $shopOrder)){
					
					$desProductLine =$pd->getAposDes($sCode);
					$list[$sCode] = $v;
					$list[$sCode]['code_product'] = $sCode;
					$list[$sCode]['DESCRIPT'] = $desProductLine['DESCRIPT'];
				}
				
			}			
		}
		
		
		
		
		
		$orderlist = $this->formatOrderCategory($list);
		
		
		$this->view->arrOrderCate = $orderCate->listAllArray();
		$addToOrder = array();

		$dateOrder = Model_DatetimeHelper::getThisWeekMonday();
		$dateBegin = Model_DatetimeHelper::getLastWeekMonday();
		$dateEnd = Model_DatetimeHelper::getLastWeekSunday();
		
		// use 2week avarage sales
		$wk2Begin = Model_DatetimeHelper::adjustWeeks("sub", $dateBegin, 1);
		$wk2End = Model_DatetimeHelper::adjustWeeks("sub", $dateEnd, 1);
				
		
		if(isset($_POST['submit'])){
			
			foreach ($_POST['add_order'] as $sCode => $value){
				$orderQty = $_POST['add_qty'][$sCode];
				if($orderQty > 0){
					$isExist = $weeklyOrder->barcodeExistInOrder($sCode, $noOrder);
		
						if(!$isExist){
		
							$desProductLine =$list[$sCode];
						
								if(!empty($desProductLine)){

									$wk1Sales = $invPro->getProductSalesQtyByDates($dateBegin, $dateEnd, $sCode);
									$wk2Sales = $invPro->getProductSalesQtyByDates($wk2Begin, $wk2End, $sCode);
		
									$isHot = $invPro->isHotItem($sCode);
									$stockShop = 0;
									$stockWarehouse = (int)$desProductLine['BALANCE'];
		
									$maxSold = $invPro->maxSoldWeeks($sCode, $dateEnd,4);
									$isNew = $pro->isNewProduct($sCode);
									$isSp = false;
										if(substr($sCode,0,2)=="SP" && substr($sCode,0,7)!="SPEAKER"){
											if($shop == "WBPC" || $shop == "WBIC" || $shop == "EPIC" || $shop == "BSIC" ){
												$isSp = true;
											}
										}
									//d($noOrder, $shop, $dateOrder, $sCode,$wk1Sales, $wk2Sales, $stockShop, $stockWarehouse, $isHot,$orderQty,$maxSold,$desProductLine['DESCRIPT']);
									
									$weeklyOrder->initalorder($noOrder, $shop, $dateOrder, $sCode,$wk1Sales, $wk2Sales, $stockShop, $stockWarehouse, $isHot,$orderQty,$maxSold,$desProductLine['DESCRIPT'],1);
									$addToOrder[$sCode]['qty'] = $orderQty;
									$addToOrder[$sCode]['des'] = $desProductLine['DESCRIPT'];
								}
						}
				}
			}
		}
		
		
		
		
		$this->view->list = $orderlist;
		$this->view->whStock = $whList;
		$this->view->shop = $shop;
		$this->view->addOrderList = $addToOrder;
	}	
		
	
	public function formatOrderCategory($arrOrderList){
	
		$cMappping = new Model_Products_Catemapping(Zend_Registry::get('db_remoteapp'));
		$product = new Model_DbTable_Productsva(Zend_Registry::get('db_remoteapp'));
	
		$arrRes = array();
		foreach($arrOrderList as $k => $v){
	
			$codeProduct = $v['code_product'];
			$pInfo = $product->getProductByBarcode($codeProduct);
	
			//d($codeProduct,$arrCategory);
			if($pInfo){
	
				$idCategory = $cMappping->getOrderCategory($pInfo['cat1'],$pInfo['cat2']);
				if(!$idCategory){
					$idCategory = 19;
				}
				$arrRes[$idCategory][] = $v;
			}else{
				$idCategory = 19;
				$arrRes[$idCategory][] = $v;
			}
	
	
	
		}
		ksort($arrRes);
		return $arrRes;
	}
	
	/**
	 * Sales Last main page is the Second step of every monday order generator 
	 * This is the landing page of print out the excel file 
	 * modify the order and verify
	 * 
	 */		
	public function salesLastWeekMainAction(){
		$this->renderScript("/products/sales-last-week-main-v2.phtml");
	}
		
		
		


	/**
	 * This function is create by leo 
	 * this is api function to get the barcode of equipment 
	 */	
	public function getEquipmentAction(){
		$this->_helper->layout->disableLayout();
		$equipment = new Model_Products_Equipment();
		$bCode = $this->_getParam('barcode');
		$desLine = $equipment->getByBarcode(trim($bCode));
		if(!$desLine) {
			echo "Equipment Description Not Available,Please Verify Barcode";
		}
		else{
			echo trim($desLine['description']).":".trim($desLine['ser_no']).":".trim($desLine['model']).":".trim($desLine['type']);
		}
	}	


	public function lastWeekDiscountAllAction(){
		
	}
	/**
	 * This is the current function to check shop sales discount 
	 * according our discount policy 
	 */
	public function lastWeekDiscountAposAction(){
		
		$fh = new Model_Fileshandler();
		$arrCase = $fh->readCaseList(getcwd()."/import/caselist.csv"); // this file still need there
		$policy = new Model_Policy();
		$arrFinal = array();
		
		$shop = $this->_getParam("shop");
		$this->view->shophead = $shop;
		
		$lastMonday = Model_DatetimeHelper::getLastWeekMonday("");
		$lastSunday = Model_DatetimeHelper::getLastWeekSunday("");
		
		$this->view->dateBegin = Model_DatetimeHelper::getLastWeekMonday();
		$this->view->dateEnd = Model_DatetimeHelper::getLastWeekSunday();
		
		$url = 'http://'.SERVER_IP_COMM.'/products/online-invoice-list-by-date/disc/yes/date_begin/'.$lastMonday.'/date_end/'.$lastSunday.'/shop/'.$shop;
		$strInv = Model_System_Downloadhelper::downloadUrl($url);
		$arrInv = unserialize(base64_decode($strInv));

		
		foreach($arrInv as $invID){
			
			// get invoice sales man, get invoice detail 
			$detailUrl = 'http://'.SERVER_IP_COMM.'/products/online-invoice-detail-by-id/shop/'.$shop.'/inv_no/'.$invID;
			$strDetail = Model_System_Downloadhelper::downloadUrl($detailUrl);
			$arrDetail = unserialize(base64_decode($strDetail));
			
			//d($arrDetail);
			
			$itemLines = $arrDetail[1];
			// this all with discount , crete the array
			
			foreach($itemLines as $lineDetail){
				
				if(stripos($arrDetail[0]['REF'],'faulty') === false){

				$tmpArr = array();
				$tmpArr[0] = $lineDetail['SCODE'];
				$tmpArr[1] = 'Category';
				$tmpArr[2] = Model_System_Downloadhelper::downloadUrl('http://'.SERVER_IP_COMM.'/products/get-old-apos-product-description/barcode/'.trim($lineDetail['SCODE']));
				$tmpArr[3] = $shop;
				$tmpArr[4] = "Shop Name";
				$tmpArr[5] = $shop;
				$tmpArr[6] = "";
				$tmpArr[7] = "Shop Name";
				$tmpArr[8] = $invID;
				$tmpArr[9] = $arrDetail[0]['DATE'];
				$tmpArr[10] = $arrDetail[0]['REF'];
				$tmpArr[11] = $lineDetail['QTY'];
				$tmpArr[12] = "PCS";
				$tmpArr[13] = "AUD";
				$tmpArr[14] = $lineDetail['PRICE'];// sales amount 
				$tmpArr[15] = $lineDetail['ITEM_DISCAMT'];// item discount 
				$tmpArr[16] = 0; // invoice disount 
				$tmpArr[17] = $lineDetail['AMOUNT']; // actual receive
				$tmpArr[18] = '';// cost 
				$tmpArr[19] = '';// gp
				$tmpArr[20] = '';// budle
				$tmpArr[21] = '';//item remark , nothing 
				$tmpArr[22] = $arrDetail[0]['SAL_CODE']; // sales man 
				$arrFinal[] = $tmpArr;
				}
			}
			
			
			
		}
		
		
		$invoice = array();
		$precent = array();
		
		foreach($arrFinal as $key => $v){
			$invoice[$key] = $v[8];
			if($v[15] > 0){
				$precent[$key] = round($v[15]/($v[15] + $v[14]),2)*100;
			}
			elseif($v[16] > 0){
				$precent[$key] = round($v[16]/$v[14],2)*100;
			}
			else{ $precent[$key] = 0;
			}
		}
		
		array_multisort($precent,SORT_DESC,$arrFinal);
		
		$arrFinal2 = array();
		$cot = count($arrFinal);
		
		for($i=0;$i<$cot;$i++)
		{
		$inv = $arrFinal[$i][8];
		if($inv!=""){
		foreach($arrFinal as $k2 => $v2){
		if($inv == $v2[8]){
		$arrFinal2[] = $v2;
			$arrFinal[$k2][8]= "";
		}
		
		}
		}
		
		}
		
		$arrFinal3 = array();
		$oldInv = "";
		$oldArray = array();
		foreach($arrFinal2 as $k3 => $v3){
		$tmpArr = $v3;
		if($v3[8] != $oldInv){
		$oldArray = array();
		$oldArray[] = $v3;
		$oldInv = $v3[8];
		}
		else{
		$oldArray[] = $v3;
		}
		echo "<br />";
		if($arrFinal2[$k3 + 1][8] != $oldInv){
			echo "<br />";
			$policyRes = $policy->calDiscount($oldArray,$arrCase);
			$tmpArr[] = $policyRes;
		
			}
			$arrFinal3[]= $tmpArr;
		}
		
		
		$this->view->arrFinal = $arrFinal3;
		
		
		// get invoice list 
		
		
		
		
		
	}
	
	/**
	 * This function is no longer in use
	 */
	public function lastWeekDiscountNewAction(){

		$fh = new Model_Fileshandler();
		$arrCase = $fh->readCaseList(getcwd()."/import/caselist.csv"); // this file still need there 
		$policy = new Model_Policy();
		$arrFinal = array();
		
		$lastMonday = Model_DatetimeHelper::getLastWeekMonday("");
		$this->view->dateBegin = Model_DatetimeHelper::getLastWeekMonday();
		$this->view->dateEnd = Model_DatetimeHelper::getLastWeekSunday();
		$lastMonday = '2015-01-05';
		$arrMatching = array(
				"BSXP" => "BSXP",
				"CLIC" => "CLIC",
				"CSIC" => "CSIC",
				"DCIC" => "DCIC",
				"FGIC" => "FGIC",
				"HPIC" => "HPIC",
				"PMIC" => "PMIC",
				"CBPC" => "CB"
		);
		
		$shop = $this->_getParam("shop");
		$this->view->shophead = $shop;
		
		$slFolder = SALES_LINE_FOLDER;
		$smFolder = SALES_MAN_FOLDER;
		
		$salesNewFileName = "SALESLINENEW".$lastMonday;
		$salesManNewFileName = "SALESMANNEW".$lastMonday;

		
		
		$arrFinal = array();
		if($shop != ""){
				
			$arrSalesMan = $fh->findSalesMan(getcwd().$smFolder."/".$salesManNewFileName,$arrMatching[$shop]);
			//var_dump($arrSalesMan);
			$arrFinal = $fh->findDiscountLastWeek(getcwd().$slFolder."/".$salesNewFileName,$arrMatching[$shop],$arrSalesMan);
				
		}		
		
		d($arrFinal);
		$invoice = array();
		$precent = array();
		
		foreach($arrFinal as $key => $v){
			$invoice[$key] = $v[8];
			if($v[15] > 0){
				$precent[$key] = round($v[15]/($v[15] + $v[14]),2)*100;
			}
			elseif($v[16] > 0){
				$precent[$key] = round($v[16]/$v[14],2)*100;
			}
			else{ $precent[$key] = 0;
			}
		}

		array_multisort($precent,SORT_DESC,$arrFinal);

		$arrFinal2 = array();
		$cot = count($arrFinal);
		
		for($i=0;$i<$cot;$i++)
		{
			$inv = $arrFinal[$i][8];
			if($inv!=""){
			foreach($arrFinal as $k2 => $v2){
				if($inv == $v2[8]){
					$arrFinal2[] = $v2;
					$arrFinal[$k2][8]= "";
				}
		
			}
		}
		
		}
		
		$arrFinal3 = array();
		$oldInv = "";
		$oldArray = array();
		foreach($arrFinal2 as $k3 => $v3){
			$tmpArr = $v3;
			if($v3[8] != $oldInv){
				$oldArray = array();
				$oldArray[] = $v3;
				$oldInv = $v3[8];
			}
			else{
				$oldArray[] = $v3;		
			}
			echo "<br />";
			if($arrFinal2[$k3 + 1][8] != $oldInv){
			echo "<br />";
				$policyRes = $policy->calDiscount($oldArray,$arrCase);
				$tmpArr[] = $policyRes;
				
			}			
			$arrFinal3[]= $tmpArr;
		}
		
		
		$this->view->arrFinal = $arrFinal3;
		
	}		


	/**
	 * warehouse batch import products into system 
	 */

	/**
	 * This is the main page Link to all saving date function
	 */

	public function importChinaOrderAction(){
		
		$imFolder = "/import/china/";
		$cpatch = getcwd();
		$fileName = "";
		
		
		$fl = new Model_Fileshandler();
		$boxNo = "A";
		$spCode = "C";
		$qty = "E";
		$comment = "F";
		$recNo = "H";
		$proCode = "I";
		$cot = 0;
		$shipDetail = new Model_DbTable_Order_Shippingdetail();
		//$shipNo = $shipDetail->getShippingNo();
		$shipment = new Model_DbTable_Order_Shipment();
		
		
		
		if($_POST){
			
			if(move_uploaded_file($_FILES['order_file']['tmp_name'], $cpatch.$imFolder.$_FILES['order_file']['name'])){
				
				$fileName = $_FILES['order_file']['name'];
				
				$pos1 = strpos($fileName,"[");
				$pos2 = strpos($fileName,"]");
				
				$str = substr($fileName,$pos1+1,$pos2-$pos1-1);
				
				$arrShipment = explode("-",$str);
				$date = explode(".",$arrShipment[0]);
				$dateShip = $date[2]."-".$date[1]."-".$date[0];
				$dateEta = Model_DatetimeHelper::adjustWeeks("add", $dateShip,1);
				
				
				$nameCourier = $arrShipment[1];
				$trackingNo = $arrShipment[2];
				
				$id = $shipment->addShipment($nameCourier, $trackingNo, $dateShip, $dateEta,null,0, "");
						
				$arrOrders = $fl->readChinaOrder($cpatch.$imFolder.$fileName);
				
				foreach($arrOrders as $oLine){
					if($cot >0 && $oLine[$proCode]!="" && $oLine[$qty] !=""){
						$shipDetail->addShippingdetail($id,$oLine[$proCode],$oLine[$qty],0, $oLine[$boxNo], $oLine[$spCode], $oLine[$recNo], $oLine[$comment]);
					}
					$cot++;
				}	
						
			}	
			
		}
				
		echo "Done , You may close the window now";
			
	}
	







		/***********************************************************************
		 * Product and price block 
		 * start 21th March
		 ***********************************************************************/
		/**
		 * list product with price on website?
		 * This function was made for whole sale reason 
		 * it may not use at the moment 
		 * 
		 */
		public function listProductsAction(){
			//$this->_helper->_layout->setLayout('layout5');			
			$products = new Model_DbTable_Productsva();
			$this->view->pList = $products->listAllProductsStockDetail();
			
		}
		public function saveProductOrderAction(){
			
			$orders = new Model_DbTable_Order_Orderlist();
			$sys = new Model_DbTable_Systemconfig();
			
			$this->_helper->_layout->setLayout('layout3');
			$this->view->strArrProducts = "";
			$this->view->orderList = "";
			$this->view->addNew = true ;
			$this->view->newOrder = "";
			
			if($_POST){
			
				$arrProductId = $_POST["id_product"];
				$strArrProducts = base64_encode(serialize($arrProductId));	
				$this->view->strArrProducts = $strArrProducts;
				
				if(isset($_POST["btn_new_order"])){

					$this->view->newOrder = $sys->runOrderCounter();
					//do nothing at the moment
				}	
				if(isset($_POST["btn_add_to_order"])){
					
					$oList = $orders->listAllUnFinallizedOrder();
					$this->view->addNew = false ;
					$this->view->orderList = $orders->listAllUnFinallizedOrder();
					
					
					
					
					
				}				
			}			
		}
		/**
		 * list product with price on website?
		 * This function was made for whole sale reason 
		 * it may not use at the moment 
		 * 
		 */
		public function listProductsPriceAction(){
			if(isset($_GET["show"]) && $_GET["show"]=="yes"){
			
			$this->_helper->_layout->setLayout('layout3');
			}
			else{
				
				
				$this->_helper->_layout->setLayout('layout_ext');
			}
			
			$this->view->pList = array();
			
			if($_GET){
				if($_GET["token"]=="031788"){
					
					$products = new Model_DbTable_Productsva();
					$pPrices = new Model_DbTable_Products_Price_Prices(); 
					$pList = $products->listAllProductsStockPrice();
			
					$this->view->pList = $pList;
				}
			}
			

		}
		/**
		 * list product with price on website?
		 * This function was made for whole sale reason
		 * it may not use at the moment
		 *
		 */
		public function saveWholeSalePriceAction(){
			
			$pPrice = new Model_DbTable_Products_Price_Prices();
			
			if($_POST){
				
				foreach($_POST as $key =>$value){
					
					if(substr($key,0,3)=="wsp"){
						
						echo $idProduct = substr($key,3);
						echo $priceWholesaleReal = $value;	
						if(!$pPrice->getPrice($idProduct)){
							$pPrice->addPrice($idProduct,null,null,null,0,Model_DatetimeHelper::dateToday());							
						}						
						$pPrice->updateWholeSalePriceReal($idProduct, $priceWholesaleReal,Model_DatetimeHelper::dateToday());
						$pPrice->updateImportPrice($idProduct,$_POST["imp"][$idProduct],2,Model_DatetimeHelper::dateToday());
						$pPrice->updateBuyPrice($idProduct,$_POST["wbp"][$idProduct],Model_DatetimeHelper::dateToday());
					}
					
				}
				
			}
			
			$this->_redirect("/products/list-products-price?token=031788&show=yes");	
		}
		
		/**
		 * list product with price on website?
		 * This function was made for whole sale reason
		 * it may not use at the moment
		 *
		 */
		public function listBarcodeAction(){
			
			$products = new Model_DbTable_Productsva();
			$this->view->productslist = $products->listAllProducts();			
		}
		
		/**
		 * temperoary funcion to import the price 
		 */
		public function zNOUSEonceoffimportpricetmpAction(){
			
			$products = new Model_DbTable_Productsva();
			$pPrice = new Model_DbTable_Products_Price_Prices();
			$margin = new Model_DbTable_Products_Price_Margin();
			
			$fn = "pc2.csv";
			
			$fl = fopen($fn,"r");
			
			while(($ld=fgetcsv($fl,0))!= FALSE){
				
				//echo $ld[0];
				$exist = $products->ifExist($ld[0]);
				if($exist){

					$idProduct = $products->getProductID(trim($ld[0]));
					$havePrice = $pPrice->getPrice($idProduct);
					if(!$havePrice){
						$pPrice->addPrice($idProduct,NULL,NULL,NULL,0,Model_DatetimeHelper::dateToday());
						//$pPrice->addPrice($idProduct,NULL , $idImportCurrency = NULL ,$updateImport = NULL  , $priceBuy , $updateBuy , $priceWholesale = NULL  , $updateWholesale = NULL  , $priceRrp = NULL  , $updateRrp = NULL )
		
					}
					
					$pPrice->updateImportPrice($idProduct, $ld[1],$ld[2],Model_DatetimeHelper::dateToday()); //2 means CNY
					//$priceWholesale = $margin->getMarginByID($idProduct,$ld[2],1);
					//$pPrice->updateWholeSalePrice($idProduct, $priceWholesale,Model_DatetimeHelper::dateToday());
				
				}
				
				
			}

		}
		
		/**
		 * After discount check , it is imporant to send the result to manager 
		 * 
		 */

		public function sendDiscountManagerAction(){
			
			$arrInv5= array(); 
			$arrInv3= array();
			$arrRes5 = array();
			$arrRes3 = array();
			
			foreach($_POST["accept"] as $key => $v){
				if($_POST["level"][$v] == 5){
					$arrInv5[] = $_POST["id_invoice"][$v];
				}
			}
			foreach($_POST["accept"] as $key => $v){
				if($_POST["level"][$v] == 3){
					$arrInv3[] = $_POST["id_invoice"][$v];
				}
			}
			
			foreach($_POST["id_invoice"] as $k2 => $v2){
				if(in_array($v2,$arrInv5)){
					$tmpArr =  array();
					$tmpArr[] = $v2;
					$tmpArr[] = $_POST["barcode"][$k2];
					$tmpArr[] = $_POST["des"][$k2];
					$tmpArr[] = $_POST["qty"][$k2];
					$tmpArr[] = $_POST["rrp"][$k2];
					$tmpArr[] = $_POST["dis"][$k2];
					$tmpArr[] = $_POST["dis_amt"][$k2];
					$tmpArr[] = $_POST["final"][$k2];
					$tmpArr[] = $_POST["sales"][$k2];
					$tmpArr[] = $_POST["remark"][$k2];
					if(isset($_POST["level"][$k2])){ $tmpArr[] = $_POST["level"][$k2];}
					$arrRes5[] = $tmpArr;
				}
				if(in_array($v2,$arrInv3)){
					$tmpArr =  array();
					$tmpArr[] = $v2;
					$tmpArr[] = $_POST["barcode"][$k2];
					$tmpArr[] = $_POST["des"][$k2];
					$tmpArr[] = $_POST["qty"][$k2];
					$tmpArr[] = $_POST["rrp"][$k2];
					$tmpArr[] = $_POST["dis"][$k2];
					$tmpArr[] = $_POST["dis_amt"][$k2];
					$tmpArr[] = $_POST["final"][$k2];
					$tmpArr[] = $_POST["sales"][$k2];
					$tmpArr[] = $_POST["remark"][$k2];
					if(isset($_POST["level"][$k2])){
						$tmpArr[] = $_POST["level"][$k2];
					}
					$arrRes3[] = $tmpArr;
				}
				
				
			}

			$mailBodyTable= '<style type="text/css">
hr.hr4 {
    background-color: #FFFFFF;
    border-bottom: 1px solid #FF0000;
    border-top: 1px dashed #FF0000;
    color: #FFFFFF;
    height: 4px;
}
</style>
<body style="font-family:Arial; font-size:12px;">
			<h1>'.$_POST["shop_head"].'  Date: '.$_POST["date_begin"].' to '.$_POST["date_end"].'</h1> 
<table width="1300" border="0" cellspacing="1" cellpadding="5" style="font-family:Arial; font-size:12px;" >
  <tr>
    <th scope="col">Invoice</th>
    <th scope="col">Barcode</th>
    <th scope="col">Description</th>
    <th scope="col">Qty</th>
    <th scope="col">RRP</th>
    <th scope="col">%Discount</th>
    <th scope="col">$Discount</th>
    <th scope="col">Final</th>
    <th scope="col">Sales</th>
    <th scope="col">Remark</th>
    <th scope="col">Level</th>
    <th scope="col">Fill Explaine Here</th>
  </tr> ';
			$oldInv = "";
			$newInv = "";
			foreach($arrRes5 as $k3 => $v3){
				$newInv = $v3[0];
				if($newInv!=$oldInv){
					$oldInv = $newInv;
					$mailBodyTable .='<tr>
    <td colspan="12"><hr class="hr4" /></td>
  </tr>';			
				}
				$strLevel = '<td>&nbsp;</td>';
				
				if(isset($v3[10])){
					
					if($v3[10] == 5){
						$strLevel = '<td style="background-color:#FF8080;">&nbsp;</td>';
					}
				}
				$mailBodyTable .='
				<tr>
    <td>'.$v3[0].'</td>
    <td>'.$v3[1].'</td>
    <td>'.$v3[2].'</td>
    <td>'.$v3[3].'</td>
    <td>'.$v3[4].'</td>
    <td>'.$v3[5].'</td>
    <td>'.$v3[6].'</td>
    <td>'.$v3[7].'</td>
    <td>'.$v3[8].'</td>
    <td>'.$v3[9].'</td>
    '.$strLevel.'
    <td>&nbsp;</td>
  </tr>';
				
			}
			
			$oldInv = "";
			$newInv = "";
			
			foreach($arrRes3 as $k4 => $v4){
				
				$newInv = $v4[0];
				
				if($newInv!=$oldInv){
					$oldInv = $newInv;
					$mailBodyTable .='<tr>
					<td colspan="12"><hr class="hr4" /></td>
					</tr>';
				}
				$strLevel = '<td>&nbsp;</td>';
			
				if(isset($v4[10])){
					if($v4[10] == 3){
						$strLevel = '<td style="background-color:#DEB363;">&nbsp;</td>';
					}
				}
				$mailBodyTable .='
				<tr>
				<td>'.$v4[0].'</td>
				<td>'.$v4[1].'</td>
				<td>'.$v4[2].'</td>
				<td>'.$v4[3].'</td>
				<td>'.$v4[4].'</td>
				<td>'.$v4[5].'</td>
				<td>'.$v4[6].'</td>
				<td>'.$v4[7].'</td>
				<td>'.$v4[8].'</td>
				<td>'.$v4[9].'</td>
				'.$strLevel.'
				<td>&nbsp;</td>
				</tr>';
			
			}

	$mailBodyTable.="</table>";

	//	echo $mailBodyTable;

	$mail = new Model_Emailshandler();
	
	$mail->sendNormalEmail($_POST["manager_email"],"Checking Discount for Your Store",$_POST["mail_comment"]."<br/>".$mailBodyTable,"office@phonecollection.com.au");
	

	echo "Email Sent, You may Now Close the window";
		}

	/**
	 * This function run on 126
	 * it show in shop item and warehouse stock 
	 * 
	 */	
	public function whCompareAction(){
		
		$shop = "WBPC";
		if($_POST){
			
			$this->_redirect("/products/wh-compare/shop/".$_POST["shop_code"]);
		}
		
		$shop = $this->_getParam("shop");
		$shopCode = $shop;
		$arrShopMaping = self::$arrShopMaping;
		
		$stock = "";
		$invPro = "";
		
		$stockOld =  Model_Aposinitnew::initProBalanceAll();
		$proDes = Model_Aposinitnew::initProDes();
		$sysCfg = new Model_DbTable_Systemconfig();
		
		$whiteList = $sysCfg->gV("WHITE_LIST");
		$blackList = $sysCfg->gV("BLACK_LIST");
		
		$arrWhite = array_map("trim",explode(",",$whiteList));
		$arrBlack = array_map("trim",explode(",",$blackList));
		
		$stock = Model_Aposinitnew::initProStock($shopCode);
		
		$invPro = Model_Aposinitnew::initAposInvPro($arrShopMaping[$shop]);
	
		$skListHave = $stockOld -> listStockWhHave();
		
		$arrRes = array();
		
		foreach($skListHave as $list){
			
			$qty = $stock->getStockBalance($list["SCODE"],$arrShopMaping[$shop]);
			//$productSold = $invPro->ifProductSold($list["SCODE"]);
			if($qty <=0 && strpos($list["SCODE"],"STA-") === false && strpos($list["SCODE"],"CREAT") === false  ){
				$ifShow = true;
				$des = $proDes->getAposDes($list["SCODE"]);
				
				// implement white black list 
				foreach($arrBlack as $blackKeyWord){
					if($blackKeyWord!=""){
					if(strpos($des["DESCRIPT"],$blackKeyWord)!== false){
						$ifShow = false;
					}	
					}
				}
				foreach($arrWhite as $whiteKeyWord){
					if($whiteKeyWord!=""){
					if(strpos($des["DESCRIPT"],$whiteKeyWord)!== false){
						$ifShow = true;
					}
					}
				}
				
				if($ifShow){
				
				$tmpArr = array();
				$tmpArr[] = $list["SCODE"];
				$tmpArr[] = $des["DESCRIPT"];
				$tmpArr[] = $list["BALANCE"];
				$arrRes[] = $tmpArr;
				
				}
			}
				
		} 
		
		//var_dump($arrRes);
		
		$this->view->arrRes = $arrRes;
		$this->view->shopCode = $shopCode;
		
	}
	/**
	 * This is also a function to compare warehouse stock and shop stock 
	 * show last sold invoice and both are 0 stock item
	 * this is the idea of recent sold out 
	 * 
	 */
	public function whCompareBothEmptyAction(){
		
		$shop = "WBPC";
		set_time_limit(0);
		if($_POST){
				
			$this->_redirect("/products/wh-compare-both-empty/shop/".$_POST["shop_code"]);
		}
		
		$shop = $this->_getParam("shop");
		
		$shopCode = $shop;
		
		$arrShopMaping = self::$arrShopMaping;
		
		$stock = "";
		$invPro = "";
		
		$stockOld =  Model_Aposinitnew::initProBalanceAll();
		$proDes = Model_Aposinitnew::initProDes();
		
		$sysCfg = new Model_DbTable_Systemconfig();
		
		$whiteList = $sysCfg->gV("WHITE_LIST");
		$blackList = $sysCfg->gV("BLACK_LIST");
		
		$arrWhite = array_map("trim",explode(",",$whiteList));
		$arrBlack = array_map("trim",explode(",",$blackList));
		
		$stock = Model_Aposinitnew::initProStock($shopCode);
		$invPro = Model_Aposinitnew::initAposInvPro($arrShopMaping[$shop]);
		
		$skListEmpty = $stockOld -> listStockWhEmpty();
		
		$arrRes = array();
		
		foreach($skListEmpty as $list){
				
			$qty = $stock->getStockBalance($list["SCODE"],$arrShopMaping[$shop]);
			
			$productSold = $invPro->ifProductSold($list["SCODE"]);
			
			if($qty <=0 && strpos($list["SCODE"],"STA-") === false && strpos($list["SCODE"],"CREAT") === false  ){
				$ifShow = true;
				$des = $proDes->getAposDes($list["SCODE"]);
		
				// implement white black list
				foreach($arrBlack as $blackKeyWord){
					if($blackKeyWord!=""){
						if(strpos($des["DESCRIPT"],$blackKeyWord)!== false){
							$ifShow = false;
						}
					}
				}
				foreach($arrWhite as $whiteKeyWord){
					if($whiteKeyWord!=""){
						if(strpos($des["DESCRIPT"],$whiteKeyWord)!== false){
							$ifShow = true;
						}
					}
				}
		
				if($ifShow){
		
					$tmpArr = array();
					$tmpArr[] = $list["SCODE"];
					$tmpArr[] = $des["DESCRIPT"];
					$tmpArr[] = $list["BALANCE"];
					$tmpArr[] = ($productSold)?$productSold:"N/A";
					$arrRes[] = $tmpArr;
		
				}
			}
		
		}
		
		$this->view->arrRes = $arrRes;
		$this->view->shopCode = $shopCode;
		
		
	}
	/**
	 * this is very long procedure of recent sold out
	 * this code need to be modified
	 */
	public function whCompareEmptyAction(){
		
		set_time_limit(0);
		ob_start();
		
		$shop = $this->_getParam("shop");
		
		$arrShopMaping = self::$arrShopMaping;
		
		$stock = "";
		
		$dateEnd = '2013-07-14';
		
		$dateBegin = Model_DatetimeHelper::adjustWeeks("sub", $dateEnd, 4);
		
		
		$stock = Model_Aposinitnew::initProBalanceAll();
		$invPd = new Model_DbTable_Apos_Newinvoice_Products_Epic(Zend_Registry::get('db_allapos'));
		
		$skListHave = $stock -> listStockWhEmpty();
		
		$arrRes = array();
		$fName = "data.csv";
		
		
		foreach($skListHave as $list){
				
			$qty = $stock->getStockBalance($list["SCODE"],$arrShopMaping[$shop]);
			$productSold = $invPd->ifProductSold($list["SCODE"]);
			if($qty > 0 && $productSold ){
		
				$tmpArr = array();
				$tmpArr[] = $list["SCODE"];
				$tmpArr[] = $list["BALANCE"];

				$barCode = $list["SCODE"];
				
				$arrRes = array();
				
				foreach ($arrShopMaping as $k => $v){
					$invPro = Model_Aposinitnew::initAposInvPro($k);
					$arrRes[] = $invPro->getProductSalesByDate($dateBegin,$dateEnd,$barCode);
				}
				
				// to answer 5 questions
				//setp 1  turnover rate given period , total sales / average inventory
				//setp 2  turnover rate shop, how many shop are saling this staff  sales shop / total shop ? this number meaning ful?
				// (if something other people sale good not in the place of hot zone?)
				//step 3  how long it can last (weeks)
				// trend average weekly sales / current stock
				//step 4  does it have a eta?
				//just need fill by china
				//step 5  is able to catch eta? how long include back order it will last
				// trend average weekly sales / Current Stock level
				//echo "<pre>";
				//var_dump($arrRes);
				//echo "</pre>";
				$tNo = count($arrRes);
				
				$totalCount = 0;
				$totalRate = 0;
				
				foreach($arrRes as $key=> $value){
					$totalCount += $value[0];
					$totalRate += $value[1];
				}
				
				
				echo "Average Count:".$totalCount / $tNo ." Average Rate:".round($totalRate / $tNo,4) * 100 ."%<br/>";
				
				flush();
				ob_flush();
			
				$tmpArr[] = $totalCount / $tNo;
				$tmpArr[] = round($totalRate / $tNo,4) * 100;
				$fl = fopen($fName,"a");
				fputcsv($fl, $tmpArr);
				fclose($fl);
				
				
				
				$arrRes[] = $tmpArr;
				
				
			}
		
		}
		
		//var_dump($arrRes);
		
		$this->view->arrRes = $arrRes;
		
	}
	/**
	 * this function is for update system whitelist and black list 
	 * the black list is for system to ignore the barcode that should NOT check
	 * the list is not automaticlly , if you want to use the list 
	 * you must write the filter in your code 
	 * this function should be in good use 
	 */
	public function scanFilterAction(){
		
		$sysCfg = new Model_DbTable_Systemconfig();
		
		$whiteList = $sysCfg->gV("WHITE_LIST");
		$blackList = $sysCfg->gV("BLACK_LIST");
		
		$this->view->whiteList = $whiteList;
		$this->view->blackList = $blackList;
		
		if($_POST){
			$sysCfg->upV("WHITE_LIST",trim($_POST["white_list"]));
			$sysCfg->upV("BLACK_LIST",trim($_POST["black_list"]));
		
			echo "Value Updated,refresh your firefox to see result";
		}
		
		
	}
	/**
	 * this is the function to run all the recent sold out list 
	 * to fill in the back order list in the extra order table
	 */
	public function soldOutCircleAction(){
		
		set_time_limit(0);
		ob_start();
		
		
		$shopArr = unserialize(ARR_SHOP_ACTIVE);
		//$shopArr=array("HPIC");
		foreach($shopArr as $shop){
			echo $str="http://".SERVER_IP_COMM."/products/shop-recent-sold-out/shop/".$shop;
			echo "<br />";
		
			$res = Model_System_Downloadhelper::downloadUrl($str);
			//sleep(1);
			echo $res;
			ob_flush();
			flush();
			//echo $date;
		}

		
	}
	
	/**
	 * This is the actually page to run the shop recent solder out 
	 */
	public function shopRecentSoldOutAction(){
		/*
		date_default_timezone_set("Australia/Melbourne");		
		
		$shop = "WBPC";
		$shop = $this->_getParam("shop");
		$shopCode = $shop;
		
		$arrSoldOut = array();
		$arrReOrder = array();
		
		$bcFilter = array("INSTALL","INSTALLATION","STRAP-","DELITEM","STA-","FAULTY","VOUCHER","PHONEREPAIR","CN");
		$arrShopMaping = unserialize(ARR_APOS_NEW_SHOP_MAPPING);

		$dateToday = Model_DatetimeHelper::dateToday();
		$dateMonday = Model_DatetimeHelper::getThisWeekMonday();
		$dateMonth = Model_DatetimeHelper::adjustWeeks("sub", $dateMonday,12);
		$dateEnd = Model_DatetimeHelper::getLastWeekSunday(); 
		
		$intDateMonth = Model_DatetimeHelper::tranferToInt($dateMonth);
		$intDateEnd = Model_DatetimeHelper::tranferToInt($dateEnd); 
		
		
		$extOrder = new Model_DbTable_Products_Stock_Extraorder(Zend_Registry::get('db_remoteapp'));
		$proDetail = new Model_DbTable_Productsva(Zend_Registry::get('db_remoteapp'));
			
		$proDes = Model_Aposinitnew::initProDes();
		$stockOld =  Model_Aposinitnew::initProBalanceAll();
		
		$stock = "";
		$invPro= "";
		$invShop = "";
		
		$sysCfg = new Model_DbTable_Systemconfig();
		
		$whiteList = $sysCfg->gV("WHITE_LIST");
		$blackList = $sysCfg->gV("BLACK_LIST");
		
		$arrWhite = array_map("trim",explode(",",$whiteList));
		$arrBlack = array_map("trim",explode(",",$blackList));

		$stock = Model_Aposinitnew::initProStock($shopCode);
		$invPro = Model_Aposinitnew::initAposInvPro($shopCode);
		//check the back order request is fullfilled
		
		$eOlist = $extOrder->listByShop($shopCode);
		foreach($eOlist as $extOrderRow){
			$stockLine = $stock->getStockBalance($extOrderRow['barcode'], $arrShopMaping[$shopCode]);
			
			if($stockLine['BALANCE']>0 && $extOrderRow['order_option']== ""){
				$extOrder->deleteExtraorder($extOrderRow['id_ext_order']);	
			}
			
			if($stockLine['BALANCE']>0 && $extOrderRow['order_fullfill']=="" &&  $extOrderRow['order_option']!=""){
				$extOrder->fullfillOrder($extOrderRow['id_ext_order']);
			}
			
			if($stockLine['BALANCE']<0 && $extOrderRow['order_option']==""){
				
				// update non handled warehouse stock 
				$whStockLine = $stockOld->getStockBalance($extOrderRow['barcode'],'WH');
				$extOrder->updateWhBalance($extOrderRow['id_ext_order'],$whStockLine['BALANCE']);
				
			}
		}
		
		//		
		$pList = $invPro->getProductSalesList($dateMonth, $dateEnd, $invPro::$_tbNames);

		foreach($pList as $sCode){
			$shopStock = $stock->getStockBalance($sCode['SCODE'], $arrShopMaping[$shopCode]);
			$shopStock = $shopStock['BALANCE'];
			$whStock = $stock->getStockBalance($sCode['SCODE'],'WH');
			$whStock = $whStock['BALANCE'];
			$ifShow = true;
			
			foreach($bcFilter as $keyword){
			
				if(strpos($sCode['SCODE'],$keyword)!== false){
					$ifShow = false;
				}
			}
			
			
			if($shopStock <= 0 && $ifShow ){
				
				$desline = $proDes->getAposDes($sCode['SCODE']);
				$disCheck = $proDetail->getProductByBarcode($sCode['SCODE']);
				$des = $desline["DESCRIPT"];
				
				if(!empty($des) && $disCheck['is_dsic']){
					if($extOrder->shouldPutIn($sCode['SCODE'], $shopCode)){
						$extOrder->addExtraorder(trim($sCode['SCODE']), $des, $shopCode, $dateToday, $whStock);	
					}
					
				}
				
				
			}
			
		}
				*/		
	}
	
	/**
	 * every time the shop analysis will take about 5 mins to run
	 * it answer 5 question
	 * 
	 * 1. recent sold out : 
	 * 2. no stock no sales
	 * 3. long time no sales 
	 * 4. never sold
	 * 5. never send
	 * 
	 * there is an annouse ment to explain what is the cause of the 5 issues 
	 * this report should be very important to the shop manager
	 * and should be summary again to the warehouse 
	 * however it is not be used quite often
	 * the report is there , the action part is not complete
	 */
	
	public function shopAnalysisAction(){
		
		set_time_limit(0);
		
		date_default_timezone_set("Australia/Melbourne");
		
		$shop = "WBPC";
		$noStockFileName1 = "NsNs1";
		
		
		$bcFilter = array("INSTALL","INSTALLATION","STRAP-","DELITEM","STA-","FAULTY","VOUCHER","PHONEREPAIR");
		
		set_time_limit(0);
		
		if($_POST){
				
			$this->_redirect("/products/shop-analysis/shop/".$_POST["shop_code"]);
		}
		
		$arrShopMaping = unserialize(ARR_APOS_NEW_SHOP_MAPPING);
		
		$dateToday = Model_DatetimeHelper::dateToday();
		$dateMonth = Model_DatetimeHelper::adjustMonths("sub",Model_DatetimeHelper::dateToday(), 1);
		$intDateMonth = Model_DatetimeHelper::tranferToInt($dateMonth);
		
		$shop = $this->_getParam("shop");
		
		$shopCode = $shop;
		
		$arrNeverSent = array();
		$arrNeverSold = array();
		$arrlongTimeNoSale = array();
		$arrNoStockNoSale = array();
		$arrNoStockNoSaleWh = array();
		$arrSoldOut = array();
		
		$proDes = Model_Aposinitnew::initProDes();
		$stockOld =  Model_Aposinitnew::initProBalanceAll();
		
		$stock = "";
		$invPro= "";
		$invShop = "";
		
		$sysCfg = new Model_DbTable_Systemconfig();
		
		$whiteList = $sysCfg->gV("WHITE_LIST");
		$blackList = $sysCfg->gV("BLACK_LIST");
		
		$arrWhite = array_map("trim",explode(",",$whiteList));
		$arrBlack = array_map("trim",explode(",",$blackList));
		
		$stock = Model_Aposinitnew::initProStock($shopCode);
		$invShop = Model_Aposinitnew::initAposInvoice($shopCode);
		$invPro = Model_Aposinitnew::initAposInvPro($shopCode);
		
		$bList = $proDes->getAll();
		
		foreach($bList as $barcode){
			//barcode
			$bcode = $barcode["SCODE"];
			$ifShow = true;
			
			foreach($bcFilter as $keyword){
				
				if(strpos($bcode,$keyword)!== false){
					$ifShow = false;
				}
			}
			
			if($ifShow){
				
			$desline = $proDes->getAposDes($bcode);
			$des = $desline["DESCRIPT"];
			//if sold 
			$invID = $invPro->ifProductSold($bcode);
			$itemStockLine = $stock->getStockBalance($bcode,$arrShopMaping[$shop]);
			$itemStock = $itemStockLine["BALANCE"];
			$whStockLine = $stockOld->getStockBalance($bcode,"WH");
			$whStock = $whStockLine["BALANCE"];
			//var_dump($invID);
			
			if($invID){
			//sold	
				$dateLine = $invShop->getInvoice($invID);
				$salesDate = $dateLine["DATE"];
				$intSaleDate = date("U",strtotime($salesDate));
				$strDate = date("Y-m-d",$intSaleDate);
				
				if($intSaleDate >= $intDateMonth ){
					//recent sold out
					if($itemStock <= 0){
						//barcode , description , invoice , warehouse stock 
						$arrSoldOut[] = array($bcode,$des,$invID,(int)$whStock,$strDate);
						
					}
					
				}else{
					//sale month ago 
					
					
					if($itemStock > 0){
						// long time no sale
						
						$arrlongTimeNoSale[] = array($bcode,$des,$invID,(int)$itemStock,(int)$whStock,$strDate);
						
					}
					else{
						// no stock no sale
						if((int)$whStock >0){
						$arrNoStockNoSale[] = array($bcode,$des,$invID,(int)$whStock,$strDate);
						}
						else{
							$arrNoStockNoSaleWh[] = array($bcode,$des,$invID,(int)$whStock,$strDate);
						}
					}
				}
				
			}
			else{
			//never sale -> get stock 
				
				if($itemStock > 0){
					//send nver sale 
					$arrNeverSold[] = array($bcode,$des,(int)$itemStock,(int)$whStock);
				}
				else{
					//never send 
					$arrNeverSent[] = array($bcode,$des,(int)$whStock);
					
				}				
			}
			
			
			//echo "<br/>";
			
			}
		}
		
		
		
		//Never Send
		//Send Never Sold
		//Date >1 month Qty > 0  long time no sale
		//date >1 month Qty <=0  No stock No sale -> warehouse stock 
		//date <1 month Qty <=0  Recent Sold out -> warehouse stock 
		
		$k1 = array();
		$k2 = array();
		
		foreach($arrSoldOut as $key => $line){
			
			$k1[$key] = $line[4];
			$k2[$key] = $line[3]; 
		}
		array_multisort($k1,SORT_ASC,$k2,SORT_DESC,$arrSoldOut);
		// no stock no sale
		
		$k1 = array();
		$k2 = array();
		
		foreach($arrNoStockNoSale as $key => $line){
				
			$k1[$key] = $line[4];
			$k2[$key] = $line[3];
		}		
		array_multisort($k1,SORT_ASC,$k2,SORT_DESC,$arrNoStockNoSale);
		
		$k1 = array();
		$k2 = array();
		$k3 = array();
		
		foreach($arrlongTimeNoSale as $key => $line){
			$k1[$key] = $line[5];
			$k2[$key] = $line[4];
			$k3[$key] = $line[3];
			
		}
		
		array_multisort($k1,SORT_ASC,$k2,SORT_DESC,$k3,SORT_DESC,$arrlongTimeNoSale);
		
		$k1 = array();
		$k2 = array();
		
		foreach($arrNeverSold as $key => $line){
		
			$k1[$key] = $line[3];
			$k2[$key] = $line[2];
		}
		array_multisort($k1,SORT_DESC,$k2,SORT_DESC,$arrNeverSold);
		
		
		$k1 = array();
		foreach($arrNeverSent as $key => $line){
		
			$k1[$key] = $line[2];
		}		
		
		array_multisort($k1,SORT_DESC,$arrNeverSent);
		
		$this->view->arrNeverSent = $arrNeverSent;
		$this->view->arrNeverSold = $arrNeverSold;
		$this->view->arrLongTimeNoSale = $arrlongTimeNoSale;
		$this->view->arrNoStockNoSale = $arrNoStockNoSale;
		$this->view->arrSoldOut = $arrSoldOut;
		$this->view->shopCode = $shopCode;
		
		
	}
	
	/**
	 * This function is no long in use , all the double start now is A0
	 * and it changes according the time 
	 * product the list which one has been removed the A0
	 */
	public function oldDoubleStarAction(){
		
		$do = $this->_getParam("do");
		
		date_default_timezone_set("Australia/Melbourne");
		
		$dateBegin = Model_DatetimeHelper::getFirstDayOfTheMonth(Model_DatetimeHelper::dateToday());
		$dateBegin = Model_DatetimeHelper::adjustMonths("sub", $dateBegin, 1);
		//$dateBegin = "2014-01-01";
		$this->view->dateBegin = $dateBegin;
		
		$products = Model_Aposinitnew::initProDes();
		$grn = new Model_DbTable_Apos_Stock_Grnold(Zend_Registry::get('db_allapos'));
		$grnData = new Model_DbTable_Apos_Stock_Grndataold(Zend_Registry::get('db_allapos'));
		
		$pList = $products->listNewProducts();
		$arrRes = array();
		
		foreach($pList as $product){
			
			//echo $product["DESCRIPT"];
			$sCode = $product["SCODE"];
			$grnNo = $grnData->getGrnNo($sCode);
			$grnDate = $grn->getGrnDate($grnNo);
			
			if(date("U",strtotime($grnDate)) < date("U",strtotime($dateBegin))  ){
				
				$tmpArr = array();
				$tmpArr[] = $sCode;
				$tmpArr[] = $product["DESCRIPT"];
				$tmpArr[] = date("Y-m-d",strtotime($grnDate));
				//echo $sCode."  ".$product["DESCRIPT"]." ".$grnDate."<br />";
				$arrRes[] = $tmpArr;
			}
			
		}
		$arrDate = array();
		
		foreach($arrRes as $k => $v){
			$arrDate[$k] = $v[2];
		}
		array_multisort($arrDate,SORT_ASC,$arrRes);
		
		$this->view->arrRes = $arrRes;
		
		//reset($arrRes);
		
		foreach($arrRes as $k2 => $v2){
			if($v2[2]!="1970-01-01"){
				if($do == "yes"){	
					$products->removeStar($v2[0]);
				}
			}
		}
		//$productsNew->removeStar("APIPADMLC001-15");
		
		//get all list with **
		
		//check the first GN of the item 
		
		//check the date of first GN see if < date begin 
		
		//Yes list it 
		
		
		
	}
	
	/**
	 * This is in order wizard step 3 as simon requst
	 */
	public function extraOrderAction(){
		
		$shopCode = $this->_getParam("shop");
		
		$extOrder = new Model_DbTable_Products_Stock_Extraorder();
		$stInfo = new Model_DbTable_Roster_Stafflogindetail();
		

		
		if($_POST){
			$stId = $stInfo->checkPasswordCorrect(Model_EncryptHelper::hashsha($_POST['pwd']));
			if($stId){
			foreach($_POST['order_option'] as $k =>$v){
							
				$extOrder->updateExtOption($k, $v, $_POST['order_qty'][$k], $stId['id']);
			}
			
			}
		}
		
		$this->view->uList = $uList = $extOrder->getUnhandledOrder($shopCode);
		$this->view->sList = $sList = $extOrder->getStopList($shopCode);
		$this->view->hList = $hList = $extOrder->getHandledOrder($shopCode);
		$this->view->fList = $fList = $extOrder->getFullfilledOrder($shopCode);
		
		//var_dump($sList,$hList);
		
		$this->renderScript("/products/extra-order-new.phtml");
		
	}
	
	/**
	 * This is to tell you who did not do the extra order
	 * this function is only notice function 
	 * 
	 */
	
	public function extraOrderNotFinishAction(){
		
		$this->view->email = $this->_getParam("email");
		$extOrder = new Model_DbTable_Products_Stock_Extraorder();
		
		$arrRes = array();
		foreach(self::$arrShopMaping as $shopCode => $v){
			$uOrderList = $extOrder->getUnhandledOrder($shopCode);
			if(count($uOrderList) > 0){
				$arrRes[$shopCode] = count($uOrderList);
				$this->view->email = 'yes';
			}else{
				$this->view->email = 'no';
			}
		}
		
		//d($arrRes);
		
		$this->view->arrRes = $arrRes;
		
	}
	/**
	 * This is the api funtion to show in company info page 
	 * that wich shop has not finish back order
	 * if the amount >20 it will show red color
	 */
	
	public function getUnhandledCountAction(){
		
		$this->_helper->layout()->disableLayout();
		
		$shopCode = $this->_getParam("shop");
		$extOrder = new Model_DbTable_Products_Stock_Extraorder();	
		echo count($extOrder->getUnhandledOrder($shopCode));
	}
	
	/**
	 * This function should be move/ copy to online 
	 * this function WAS for online product finder 
	 * see if the product has the picture 
	 * if not give a list 
	 */
	public function checkMissingPictureAction(){
		
		set_time_limit(0);
		ob_start();
		$pro = Model_Aposinitnew::initProDes();
		$pList = $pro->getAll();
		foreach($pList as $product){
			//echo $product["SCODE"]."<br />";
			$url = "http://".WEB_IP."/product_img/home_img/".trim($product["SCODE"])."_0.jpg";
			$result = Model_Fileshandler::checkimg($url);
			//var_dump($result);
			if(!$result){
				echo $product["SCODE"]."|".$product["DESCRIPT"]."<br />";
				ob_flush();
			}			
		}
	}
	/**
	 * This is done by Leo ,run every day /week , if item in apos 
	 * 1.For match all apos product code in product_v1, if not add product
	 * 2.For match all apos got stock products in product_v1_stock, if not add product
	 * 3.For check all prodcut_v1 with product title;
	 * 
	 * @author Leo
	 * @version 2014-07-25
	 */
	public function checkProductInAposAction(){
		$this->_helper->layout()->disableLayout();
		//Kint::enabled(false);
		date_default_timezone_set('Australia/Melbourne');
		$today = date('Y-m-d', time());
		$productOld = Model_Aposinitnew::initProDes();
		$productAposStock = Model_Aposinitnew::initProBalanceAll();
		$productDb = new Model_DbTable_Productsva(Zend_Registry::get('db_remoteapp'));
		$productStock = new Model_DbTable_Productstock(Zend_Registry::get('db_remoteapp'));
		$Productapos = $productOld->getAll();
		$aposStock = $productAposStock->listStockWhHave();
		$missProduct = array();
		$missStockProduct = array();
		
		foreach($Productapos as $k => $v){
			$tmpArr = array();
			if($v['CAT']!='STATI'&& $v['CAT']!='SERVI' && $v['CAT']!='SERV' && $v['CAT']!= 'CRAZY'){
				if($productDb->ifExist(trim($v['SCODE']))==false){
					$tmpArr['code_product'] = trim($v['SCODE']);
					$tmpArr['title_product'] = trim($v['DESCRIPT']);
					$missProduct[] = $tmpArr;
				}
			}
		}
		
		if($missProduct!= null){
			foreach($missProduct as $k2 => $v2){
				$productDb->addProduct($v2['code_product'], $v2['title_product']);
			}
		}
		
		if(isset($_POST['miss_detail'])){
			$productList = $productDb->listAllProducts();
			$missDetail = array();
			foreach($productList as $k4 => $v4){
				if($v4['title_product']==null){
					$missDetail[] = $v4;
				}
			}
			
			$title = array('id_product','code_product','title_product');
			$this->renderScript('/products/exportCsv.phtml');
			
			$filename = date('Ymd');
			header("Content-type: text/csv");
			header("Content-Disposition: attachment; filename={$filename}.csv");
			header("Pragma: no-cache");
			header("Expires: 0");
			$outputBuffer = fopen("php://output", 'w');
				
			fputcsv($outputBuffer,$title);
			
			foreach($missDetail as $k3 => $val3){
				$myarray = array();
				$myarray['id_product'] = $val3['id_product'];
				$myarray['code_product'] = $val3['code_product'];
				$myarray['title_product'] = $val3['title_product'];
			
				fputcsv($outputBuffer, $myarray);
			
			}
			
			fclose($outputBuffer);
			

		}
		foreach ($aposStock as $k3 => $v3){
			$id = $productDb->getProductID(trim($v3['SCODE']));
			$tmpArr2 = array();
			if($productStock->idExist($id)==false){
				$tmpArr2['id_prodcut'] = $id;
				$tmpArr2['code_product'] = trim($v3['SCODE']);
				$tmpArr2['balance'] = (int)$v3['BALANCE'];
				$missStockProduct[] = $tmpArr2;
			}
						
		}
		
		
		foreach($missStockProduct as $k6 => $v6){
			$productStock->insertStockWarehouse($v6['id_prodcut'], $v6['balance']);
		}
		
		
		
		if(isset($_POST['get_all'])){
			
				$exportData = array();
				$allStockList = $productStock->listAll();
				foreach($allStockList as $k5 => $v5){
					$tmpArr = array();
					$tmpArr['id_product'] = $v5['id_product'];
					$pDetail = $productDb->getProduct($v5['id_product']);
					$tmpArr['code_product'] = $pDetail['code_product'];
					$tmpArr['title_product'] = $pDetail['title_product'];
					$tmpArr['price_rrp'] = $v5['price_rrp'];
					$exportData[] = $tmpArr;
				}
				$title = array('id_product','code_product','title_product','Product_RRP');
				$this->renderScript('/products/exportCsv.phtml');
				
				$filename = date('Ymd');
				header("Content-type: text/csv");
				header("Content-Disposition: attachment; filename={$filename}.csv");
				header("Pragma: no-cache");
				header("Expires: 0");
				$outputBuffer = fopen("php://output", 'w');
					
				fputcsv($outputBuffer,$title);
				
				foreach($exportData as $k3 => $val3){
					$myarray = array();
					$myarray['id_product'] = $val3['id_product'];
					$myarray['code_product'] = $val3['code_product'];
					$myarray['title_product'] = $val3['title_product'];
					$myarray['Product_RRP'] = $val3['price_rrp'];
				
					fputcsv($outputBuffer, $myarray);
				
				}
				
				fclose($outputBuffer);

		}

	}
	
	/**
	 * This one is to product overstock list for hot cold item in 8 weeks time 
	 */

	public function overStockListAction(){
		
		set_time_limit(0);
		
		$b_time = microtime(true);
		
		$intEightWeekAgo =Model_DatetimeHelper::tranferToInt(Model_DatetimeHelper::adjustDays("sub",Model_DatetimeHelper::getLastWeekSunday(), 80));
		
		$arrShopMaping = self::$arrShopMaping;
		
		
		$shop = "HPPC";
		$shop = $this->_getParam("shop");
		
		$proDes = Model_Aposinitnew::initProDes();
		
		$stock = Model_Aposinitnew::initProStock($shop);
		$invPro = Model_Aposinitnew::initAposInvPro($shop);
						
		$pList = $proDes->getAll();
		
		$arrRes = array();
		$arrRes2 = array();
		
		$arrHot = array();
		$arrNormal = array();
		$arrCold = array();
		$arrCodeSort = array();
		$arrVCold = array();
		$arrVColdSort = array();
		$arrNormalSort = array();
		$arrHotSort = array();
		
		
		
		$pros = new Model_DbTable_Productsva(Zend_Registry::get('db_remoteapp'));
		$cot = 0;
		
		foreach($pList as $pro){

			$sCode = trim($pro["SCODE"]);
			
			
			$id = $pros->getProductID(trim($sCode));
			$line = $pros->getProduct($id);
			$dateIntro = Model_DatetimeHelper::tranferToInt($line['date_introduce']);
			//if($dateIntro <= $intEightWeekAgo){ echo "Smaller";}
			//else{ echo "New P";}
			
			if(!$id){
				
				echo $sCode."<br />";
			}
			if(trim(substr($sCode,0,4)) != "STA-" && $dateIntro <= $intEightWeekAgo && $id!==false ){
				
				// if not sta and Old products
				
				$stockLine = $stock->getStockBalance($sCode, $arrShopMaping[$shop]);
				$whStock = $stock->getStockBalance($sCode,"WH");	
				$isHot = $invPro->isHotItem10Wk($sCode);
				//echo $isHot;
				
				if($isHot== "VERYCOLD" && $stockLine['BALANCE'] >0 ){
					
					$arrVCold[]= array($sCode,$stockLine['BALANCE']);
					$arrVColdSort[] = $stockLine['BALANCE'];
					
					$cot++;
				}
				
				if($isHot== "COLD" && $stockLine['BALANCE'] >0 ){
						
					$arrCold[]= array($sCode,$stockLine['BALANCE']);
					$arrColdSort[] = $stockLine['BALANCE'];
						
					//$cot++;
				}

				if($isHot== "NORMAL" && $stockLine['BALANCE'] >0 ){
				
					$arrNormal[]= array($sCode,$stockLine['BALANCE']);
					$arrNormalSort[] = $stockLine['BALANCE'];
				
					//$cot++;
				}
				
				if($isHot== "HOT" && $stockLine['BALANCE'] >0 ){
				
					$arrHot[]= array($sCode,$stockLine['BALANCE']);
					$arrHotSort[] = $stockLine['BALANCE'];
				
					//$cot++;
				}
					
			}

			
		}
		array_multisort($arrVColdSort,SORT_DESC,$arrVCold);
		array_multisort($arrColdSort,SORT_DESC,$arrCold);
		array_multisort($arrNormalSort,SORT_DESC,$arrNormal);
		array_multisort($arrHotSort,SORT_DESC,$arrHot);
		$this->view->arrRes = $arrVCold;
		
		$fnVCold = $shop."_vcold.csv";
		$fnCold =  $shop."_cold.csv";
		$fnNormal =  $shop."_normal.csv";
		$fnHot =  $shop."_hot.csv";
		
		$fl = fopen($fnVCold,"a");
		
		foreach($arrVCold as $key => $v){
			
			$proDesLine = $proDes->getAposDes($v[0]);
			fputcsv($fl,array($v[0],$proDesLine['DESCRIPT'],$v[1],$proDesLine['CAT2'],$proDesLine['CAT3']));			
		}
		fclose($fl);
		
		$fl2 = fopen($fnCold,"a");

		foreach($arrCold as $key2 => $v2){
				
			$proDesLine = $proDes->getAposDes($v2[0]);
			fputcsv($fl2,array($v2[0],$proDesLine['DESCRIPT'],$v2[1],$proDesLine['CAT2'],$proDesLine['CAT3']));
		}
		fclose($fl2);
		
		$fl3 = fopen($fnNormal,"a");
		
		foreach($arrNormal as $key3 => $v3){
		
			$proDesLine = $proDes->getAposDes($v3[0]);
			fputcsv($fl3,array($v3[0],$proDesLine['DESCRIPT'],$v3[1],$proDesLine['CAT2'],$proDesLine['CAT3']));
		}
		fclose($fl3);

		
		$fl4 = fopen($fnHot,"a");
		
		foreach($arrHot as $key4 => $v4){
		
			$proDesLine = $proDes->getAposDes($v4[0]);
			fputcsv($fl4,array($v4[0],$proDesLine['DESCRIPT'],$v4[1],$proDesLine['CAT2'],$proDesLine['CAT3']));
		}
		fclose($fl4);
				
		//var_dump($arrRes);
		
		//$pList = $invPro->
		
		$e_time = microtime(true);
		
		$dif = $e_time - $b_time;
		echo "TIME:".$dif;
		
	}
	
	/**
	 * This is the summary function that shop decide stop sales
	 */
	public function stopSaleListAction(){
		$shop = $this->_getParam("shop");
		
		$extOrder = new Model_DbTable_Products_Stock_Extraorder();
		$sList = $extOrder->getStopSale($shop);
		
		$this->view->sList = $sList;
		
	}
	
	/**
	 * This is the function list back order for shop
	 */
	
	public function backOrderListAction(){
		
		$shop = $this->_getParam("shop");
		
		$reOrder = new Model_DbTable_Products_Stock_Reorder();
		
		$rList = $reOrder->getReorderByShop($shop);
		$this->view->rList = $rList;
				
	}
	
	/**
	 * This function run to make the apos invoice active 
	 * to solve the problem that some invoice in in-active status and 
	 * the stock did not deduct 
	 */
	public function activeCircleAction(){
		set_time_limit(0);
		ob_start();
		$shopArr = unserialize(ARR_SHOP_ACTIVE);
		foreach($shopArr as $shop){
			echo $str="http://localhost/products/active-shop-invoice/shop/".$shop;
			echo "<br />";
		
			$res = Model_System_Downloadhelper::downloadUrl($str);
			//sleep(1);
			echo $res;
			ob_flush();
			flush();
			//echo $date;
		}
		
	}
	
	/**
	 * This is the actual page to active the apos invoice 
	 */
	public function activeShopInvoiceAction(){
	
		$shopHead = $this->_getParam("shop");
		$arrShopMaping =self::$arrShopMaping;
	
		$inv = "";
		$inv = Model_Aposinitnew::initAposInvoice($shopHead);

		
		$inv->activeInvoice();
	
	}
	
	/**
	 * This was in the order procedure , may not be useable any more
	 */
	public function getShippingDetailAction(){
		
		$arrShippingOrder = array(1,2);
		
		$pros = new Model_DbTable_Productsva();
		$proShip = new Model_DbTable_Order_Shippingdetail();
		$pList = $pros->listAllProducts();
		
		$arrRes = array();
		
		
		foreach($pList as $product){
			
			$arrDetail["code_product"] = $product['code_product'];
			
			$arrDetail += $proShip->getShippingQty($product['code_product'], $arrShippingOrder);

			$arrRes[] = $arrDetail; 
		}
		$this->view->arrRes = $arrRes;
		//var_dump($arrRes);
	}
	/**
	 * This is calculation for jeffrey to get last 8 weeks product sales
	 */
	public function lastEightWeeksProductsSalesAction(){
		
		set_time_limit(0);
				
		$time_start = microtime(true);
		
		$arrShopMaping = self::$arrShopMaping;
		$shopArr = unserialize(ARR_SHOP_ACTIVE);
		$pro = new Model_DbTable_Productsva(Zend_Registry::get('db_remoteapp'));
		$pSales = new Model_DbTable_Products_Sales(Zend_Registry::get('db_remoteapp'));
		
		$pStock = Model_Aposinitnew::initProBalanceAll();
		
		$pSales->deleteAll();
		$proList = $pro->listAllProductsNew();		
		
		$product = "";
		
		$dateBegin = Model_DatetimeHelper::getLastWeekMonday();
		$dateEnd = Model_DatetimeHelper::getLastWeekSunday();
		
		$actDateBegin = "";
		$actDateEnd = "";
	
		$cot = 0;
		
		foreach($proList as $product ){
			
			if(!self::bCodeFilter($product['code_product'])){
			
			$arrPSales = array();
			if($cot < 5000){
			for($i=0;$i<=7;$i++){

				$actDateBegin = Model_DatetimeHelper::adjustWeeks("sub", $dateBegin, $i);
				$actDateEnd = Model_DatetimeHelper::adjustWeeks("sub", $dateEnd, $i);
				
				$totalSales = 0;
				$totalShopStock = 0;
				
				foreach($shopArr as $shop){	
					
					$stockShop = Model_Aposinitnew::initProStock($shop);
					$shopStock = $stockShop->getStockBalance(trim($product['code_product']),$arrShopMaping[$shop]);
					$totalShopStock += ($shopStock['BALANCE'])?$shopStock['BALANCE']:0;
					$invPro = Model_Aposinitnew::initAposInvPro($shop);
					
					$sales = $invPro->getProductSalesQtyByDates($actDateBegin ,$actDateEnd,trim($product['code_product']));
					
					//var_dump($sales);
					$totalSales +=$sales;	
				}				
				
				$arrPSales[$i]=$totalSales;
			}
			//var_dump($arrPSales);
			$stockWh = 0;
			
			$arrStockWh = $pStock->getStockBalance($product['code_product'],'WH');
			$stockWh = ($arrStockWh['BALANCE'])?$arrStockWh['BALANCE']:0;
			
			$pSales->addSales($product['code_product'], $arrPSales[0], $arrPSales[1], $arrPSales[2], $arrPSales[3], $arrPSales[4], $arrPSales[5], $arrPSales[6], $arrPSales[7],$stockWh,$totalShopStock);
			
			}
			}
			//ob_start();
			//echo $cot++;
			//flush();
			//ob_flush();
			
		}
		
		echo 'Total execution time in seconds: ' . (microtime(true) - $time_start);
	
	}
	/**
	 * after product sales , it update the shop / warehouse stock to the sales table
	 */
	public function updateWhShopStockAction(){
		
		set_time_limit(0);
		
		
		$arrShopMaping = self::$arrShopMaping;
		$shopArr = unserialize(ARR_SHOP_ACTIVE);
		$pSales = new Model_DbTable_Products_Sales(Zend_Registry::get('db_remoteapp'));
		
		$pStock = Model_Aposinitnew::initProBalanceAll();		
		
		$pList = $pSales->listAll();
		foreach($pList as $key => $v){
			
			$codeProduct = $v["code_product"];
			$idSales = $v["id_sales"];
			
			$totalShopStock = 0;
			
			foreach($shopArr as $shop){
					
				$stockShop = Model_Aposinitnew::initProStock($shop);
				$shopStock = $stockShop->getStockBalance($codeProduct,$arrShopMaping[$shop]);
				$totalShopStock += ($shopStock['BALANCE'])?$shopStock['BALANCE']:0;
			}
			
			$stockWh = 0;
				
			$arrStockWh = $pStock->getStockBalance($codeProduct,'WH');
			$stockWh = ($arrStockWh['BALANCE'])?$arrStockWh['BALANCE']:0;
			
			$pSales->updateStock($idSales, $stockWh, $totalShopStock);
					
		}
		
	}
	/**
	 * not only need to record the sales , it also need to record the how many KT for this product in the week
	 * may be the KT is not active so the stock for warehouse is not accurate
	 */
	public function patchKtAction(){
		set_time_limit(0);
		$pSales = new Model_DbTable_Products_Sales(Zend_Registry::get('db_remoteapp'));
		$tOld = new Model_DbTable_Apos_Stock_Ktdataold(Zend_Registry::get('db_allapos'));
		$pList = $pSales->listAll();	

		foreach($pList as $k => $v){
			$sCode = trim($v['code_product']);
			
			$resOld = $tOld->thisWeekTransfer($sCode);
			
			$pSales->updateKt($v['id_sales'],$resOld);
			
		}
		
	}
	/**
	 * This is made by leo
	 * This one is run on 126 for simon of pupolar list 
	 * Simon can choose the product as pop or remove it from pop list 
	 * 
	 */
	public function popListAction(){
		$productOld = Model_Aposinitnew::initProDes();
		$productAposStock = Model_Aposinitnew::initProBalanceAll();
		$productDb = new Model_DbTable_Productsva(Zend_Registry::get('db_remoteapp'));
		$Productapos = $productOld->getAll();
		$productList = array();

		foreach($Productapos as $k => $v){
			$tmpArr = array();
			if($v['CAT']!='STATI'&& $v['CAT']!='SERVI' && $v['CAT']!='SERV' && $v['CAT']!= 'CRAZY'&& $v['CAT'] != 'SERV'){
					$pId = $productDb->getProductID(trim($v['SCODE']));
					if($pId){
						$pDetail = $productDb->getProduct($pId);
						$tmpArr['code_product'] = trim($v['SCODE']);
						$tmpArr['title_product'] = trim($v['DESCRIPT']);
						$tmpArr['cate'] = trim($v['CAT']);
						$tmpArr['status'] = $pDetail['is_pop'];
					}else{
						$tmpArr['code_product'] = trim($v['SCODE']);
						$tmpArr['title_product'] = trim($v['DESCRIPT']);
						$tmpArr['cate'] = trim($v['CAT']);
						$tmpArr['status'] = null;
					}
					$productList[] = $tmpArr;
			}
		}
		$this->view->popList = $productList;
		
		if(isset($_POST['submit'])){
			foreach ($_POST['popStatus'] as $k => $v){
				if($v == 'pop'){
					$productDb->popAction($k, $v);
				}elseif($v == 'remove'){
					$productDb->popAction($k, $v);
				}
			}
			$url = "/products/pop-list";
			$this->_redirect($url);
		}
	}
	
	/**
	 * this is very old function to get stock and the stock on the sea
	 * so it show how long the stock can hold 
	 */
	
	public function stockAnalysisAction(){
		set_time_limit(0);
		$pSales = new Model_DbTable_Products_Sales();
		
		$sDetail = new Model_DbTable_Order_Shippingdetail();
		$shipment = new Model_DbTable_Order_Shipment();
		
		$sList = $shipment->getOnTheSea();
		
		$arrShip = array();
		foreach($sList as $key => $ship){
			
			$arrShip[$ship['id_shipment']] = $ship['date_ship'];
		}
		
		
		//$ship = new Model_DbTable_Shipment();
		
		//$arrShip = array(
		//		 1 => "2013-09-01",
		//		 2 => "2013-10-11"
		//		);
		
		
		
		$pList = $pSales->listAll();
		
		$this->view->pList = $pList;
		$this->view->arrShip = $arrShip;
	}

	/**
	 * This is the function to generate weekly order 
	 * this function should not be use any more 
	 * it using too much memory 
	 */
	public function weeklyOrderCircleAction(){
		set_time_limit(0);
		ob_start();
		
		
		$shopArr = array("ADPC","BBPC","BHPC","BSPC","BSIC","CBPC","CLPC","EPPC","KCPC","NLPC","PMPC","SLIC","WBPC","WBIC","WLIC","WGIC","WGPC","CSIC","CLIC","DCIC","PMIC","BSXP","FGIC","HPIC");
		//$shopArr=array("HPIC");
		foreach($shopArr as $shop){
			echo $str="http://".SERVER_IP_COMM."/products/generate-weeks-order/shop/".$shop;
			echo "<br />";
		
			$res = Model_System_Downloadhelper::downloadUrl($str);
			//sleep(1);
			echo $res;
			ob_flush();
			flush();
			//echo $date;
		}
		
	}
	/**
	 * Generate Order Weekly, Re-factory on 2014-0708
	 * Will not directly Export to Excel now, will only show on the screen waiting to modify
	 * after modify done , click export button , then it will exported to the place 
	 * @auther Norman
	 * @version 2014-07-10
	 * 
	 */
	
	public function showWeeksOrderAction(){
		
		
		set_time_limit(0);
		
		$shop = $this->_getParam("shop");
		$isSpecial = $this->_getParam("spod");
		//$generate = $this->_getParam("gen");
		
		// Check if it is specail Order
		if($isSpecial == "yes"){
			$isSpecial =true;
		}
		else{
			$isSpecial = false;
		}
		/**
		 * For Product OrDer / Special orDer
		 * PD: Order Date Mondy of the Week, Order for Last week Monday/Sunday
		 * SD: Order Date TODAY, order From lastweek monday to yesterday
		 */
		$preFix = "PD";
		$datePD = Model_DatetimeHelper::getThisWeekMonday("");
		$dateOrder = Model_DatetimeHelper::getThisWeekMonday();
		
		$dateBegin = Model_DatetimeHelper::getLastWeekMonday();
		$dateEnd = Model_DatetimeHelper::getLastWeekSunday();
		if($isSpecial){
		
			$preFix = "SD"; // special second order
			$datePD = Model_DatetimeHelper::dateToday(""); //thursday order
			$dateOrder = Model_DatetimeHelper::dateToday();
				
			$dateBegin = Model_DatetimeHelper::getLastWeekMonday(); // special order
			$dateEnd = Model_DatetimeHelper::dateYesterday(); // special order
				
				
		}
		
		
		// use 2week avarage sales
		$wk2Begin = Model_DatetimeHelper::adjustWeeks("sub", $dateBegin, 1);
		$wk2End = Model_DatetimeHelper::adjustWeeks("sub", $dateEnd, 1);
		
		$weeklyOrder = new Model_DbTable_Order_Weeklyorder(Zend_Registry::get('db_remoteapp'));
		$orderSold = new Model_DbTable_Products_Stock_Extraorder(Zend_Registry::get('db_remoteapp'));
		$orderSpecial = new Model_Products_Adjustment(Zend_Registry::get('db_remoteapp'));
		
		$stock = Model_Aposinitnew::initProStock($shop);
		$stockWh = Model_Aposinitnew::initProBalanceAll();
		$pd = Model_Aposinitnew::initProDes();
		
		$pro = new Model_DbTable_Productsva(Zend_Registry::get('db_remoteapp'));
		
		
		$noOrder = $preFix.$shop.$datePD;
		
		$invPro = Model_Aposinitnew::initAposInvPro($shop);
		$pList = $invPro->getProductSalesList($dateBegin,$dateEnd,$invPro::$_tbNames);
		$arrWithQtyOrderExtra = $orderSold->getUnhandleExtraOrderWithQty($shop);
		$arrWithQtyOrderSpecial = $orderSpecial->listSpecialOrder($noOrder);
			
			
			// check if add barcode
			//check barcode in the ordr ?
			// if not inital order
				
			if(isset($_POST['btn_add_code'])){
		
				$sCode = trim($_POST['code_add']);
		
				$isExist = $weeklyOrder->barcodeExistInOrder($sCode, $noOrder);
		
				if(!$isExist){
		
					$desProductLine =$pd->getAposDes($sCode);
					
					if(!empty($desProductLine)){
					$stockShop = 0;
					$stockWarehouse = 0;
		
					$wk1Sales = $invPro->getProductSalesQtyByDates($dateBegin, $dateEnd, $sCode);
					$wk2Sales = $invPro->getProductSalesQtyByDates($wk2Begin, $wk2End, $sCode);
		
					//dd($wk1Sales,$wk2Sales);
		
					$isHot = $invPro->isHotItem($sCode);
						
					$stShopLine = $stock->getStockBalance($sCode, self::$arrShopMaping[$shop]);
					$stockShop = ($stShopLine)?$stShopLine['BALANCE']:0;
						
					$stWhLine = $stockWh->getStockBalance($sCode,'WH');
					$stockWarehouse = ($stWhLine)?$stWhLine['BALANCE']:0;
						
					$maxSold = $invPro->maxSoldWeeks($sCode, $dateEnd,4);
					$isNew = $pro->isNewProduct($sCode);
					$isSp = false;
					if(substr($sCode,0,2)=="SP" && substr($sCode,0,7)!="SPEAKER"){
						if($shop == "WBPC" || $shop == "WBIC" || $shop == "EPIC" || $shop == "BSIC" ){
							$isSp = true;
						}
					}
					$orderQty = $invPro->calOrderQty($wk1Sales, $wk2Sales, $stockShop, $isHot,$maxSold,$isNew,$isSp);
		
					
		
					$weeklyOrder->initalorder($noOrder, $shop, $dateOrder, $sCode,$wk1Sales, $wk2Sales, $stockShop, $stockWarehouse, $isHot,$orderQty,$maxSold,$desProductLine['DESCRIPT'],1);
					}else{
						echo '<script>alert("No such Item, it may stop selling");</script>';
					}
				}
			}
		
				
			// check if update Qty
			if(isset($_POST['btn_save']) || isset($_POST['btn_save2'])  ){
				/*
				 foreach($_POST['qty_order'] as $idOrder => $orderQty){
				$weeklyOrder->reviseQty($idOrder, $orderQty);
				}
				*/
		
				foreach($_POST['qty_order_shop'] as $idOrder => $orderQty){
					$weeklyOrder->reviseQtyShop($idOrder, $orderQty);
				}
				foreach($_POST['qty_wh_stock'] as $idOrder => $qty){
					$weeklyOrder->reviseQtyWH($idOrder, $qty);
				}
				
			}

		
		
		$orderList = $weeklyOrder->getOrderByNo($noOrder);
	
		
		//d($orderList);
		
		$this->view->orderList = $orderList;
		
		
		$remoteUrl = "http://".WEB_IP."/products/export-weeks-order/shop/".$shop;
		
		if($isSpecial){
				
			$remoteUrl = "http://".WEB_IP."/products/export-weeks-order/spod/yes/shop/".$shop;
		}
	
		if($_POST && isset($_POST['btn_gen_excel'])){
		
			$this->_redirect($remoteUrl);
		}
		
		
	}
	
	/**
	 * This is the function to generate the weekly order for shop
	 * only warehouse will generate the order then shop can modify it 
	 */
	
	
	public function generateWeeksOrderAction(){
		
		set_time_limit(0);
		
		$shop = $this->_getParam("shop");
		$isSpecial = $this->_getParam("spod");
		$generate = $this->_getParam("gen");
		
		// Check if it is specail Order 
		if($isSpecial == "yes"){$isSpecial =true;}
		else{	
			$isSpecial = false;
		}
		/**
		 * For Product OrDer / Special orDer
		 * PD: Order Date Mondy of the Week, Order for Last week Monday/Sunday
		 * SD: Order Date TODAY, order From lastweek monday to yesterday
		 */
		$preFix = "PD";
		$datePD = Model_DatetimeHelper::getThisWeekMonday("");
		$dateOrder = Model_DatetimeHelper::getThisWeekMonday();
		
		$dateBegin = Model_DatetimeHelper::getLastWeekMonday();
		$dateEnd = Model_DatetimeHelper::getLastWeekSunday();
		if($isSpecial){
		
			$preFix = "SD"; // special second order 
			$datePD = Model_DatetimeHelper::dateToday(""); //thursday order
			$dateOrder = Model_DatetimeHelper::dateToday();
			
			$dateBegin = Model_DatetimeHelper::getLastWeekMonday(); // special order
			$dateEnd = Model_DatetimeHelper::dateYesterday(); // special order
			
			
		}
		
		
		// use 2week avarage sales
		$wk2Begin = Model_DatetimeHelper::adjustWeeks("sub", $dateBegin, 1);
		$wk2End = Model_DatetimeHelper::adjustWeeks("sub", $dateEnd, 1);
		
		$weeklyOrder = new Model_DbTable_Order_Weeklyorder(Zend_Registry::get('db_remoteapp'));
		$orderSold = new Model_DbTable_Products_Stock_Extraorder(Zend_Registry::get('db_remoteapp'));
		$orderSpecial = new Model_Products_Adjustment(Zend_Registry::get('db_remoteapp'));
		$proDetail = new Model_DbTable_Productsva(Zend_Registry::get('db_remoteapp'));
		
		$stock = Model_Aposinitnew::initProStock($shop);
		$stockWh = Model_Aposinitnew::initProBalanceAll();
		$pd = Model_Aposinitnew::initProDes();
		
		$pro = new Model_DbTable_Productsva(Zend_Registry::get('db_remoteapp'));
		

		$noOrder = $preFix.$shop.$datePD;
	
		$invPro = Model_Aposinitnew::initAposInvPro($shop);
		if($shop == 'CLIC'){
			$invPro = Model_Aposinitnew::initAposInvPro('CLPC');
		}
		$pList = $invPro->getProductSalesList($dateBegin,$dateEnd,$invPro::$_tbNames);
		$arrWithQtyOrderExtra = $orderSold->getUnhandleExtraOrderWithQty($shop);
		$arrWithQtyOrderSpecial = $orderSpecial->listSpecialOrder($noOrder);
		
		if(!$_POST && $generate == "yes"){
			// remove order number and re-generate
			$weeklyOrder->purgeOrder($noOrder);

		// Weekly Order is What Been Sold Last Week 	
			
		foreach($pList as $key => $v){
			
			$stockShop = 0;
			$stockWarehouse = 0;

			$sCode = trim($v['SCODE']);
			$wk2Sales = $invPro->getProductSalesQtyByDates($wk2Begin, $wk2End, $sCode);
			$isHot = $invPro->isHotItem($sCode);
			
			$stShopLine = $stock->getStockBalance($sCode, self::$arrShopMaping[$shop]);
			$stockShop = ($stShopLine)?$stShopLine['BALANCE']:0;
			
			$stWhLine = $stockWh->getStockBalance($sCode,'WH');
			$stockWarehouse = ($stWhLine)?$stWhLine['BALANCE']:0;
			
			$maxSold = $invPro->maxSoldWeeks($sCode, $dateEnd,4);
			$isNew = $pro->isNewProduct($sCode);
			$isSp = false;
			if(substr($sCode,0,2)=="SP" && substr($sCode,0,7)!="SPEAKER"){
				if($shop == "WBPC" || $shop == "WBIC" || $shop == "EPIC" || $shop == "BSIC" ){
					$isSp = true;
				}	
			}
			$orderQty = $invPro->calOrderQty((int)$v["SOLDQTY"], $wk2Sales, $stockShop, $isHot,$maxSold,$isNew,$isSp);

			if(!in_array($sCode,self::$arrbarCodeFilter)){
				
				$desProductLine =$pd->getAposDes($sCode);
				if(!empty($desProductLine)){
					$weeklyOrder->initalorder($noOrder, $shop, $dateOrder, $sCode,(int)$v["SOLDQTY"], $wk2Sales, $stockShop, $stockWarehouse, $isHot,$orderQty,$maxSold,$desProductLine['DESCRIPT']);
				}
			}
		}
		
		//  Extra Order , Non - Fullfilled  Exra Order 
		if($arrWithQtyOrderExtra){
		foreach($arrWithQtyOrderExtra as $k2 => $v2){
			
			$stockShop      = 0; // it is sold out so 100% zero
			$stockWarehouse = 0;
			$sCode          = trim($v2['barcode']);
			$orderQty       = trim($v2['qty']);
			
			$isExist = $weeklyOrder->barcodeExistInOrder($sCode, $noOrder);
			
			if( !$isExist ){
				

			$wk1Sales = $invPro->getProductSalesQtyByDates($dateBegin, $dateEnd, $sCode);
			$wk2Sales = $invPro->getProductSalesQtyByDates($wk2Begin, $wk2End, $sCode);
			$isHot    = $invPro->isHotItem($sCode);
			
			$stWhLine = $stockWh->getStockBalance($sCode,'WH');
			$stockWarehouse = ($stWhLine)?$stWhLine['BALANCE']:0;
			
			$maxSold = $invPro->maxSoldWeeks($sCode, $dateEnd,4);
			
			if(!in_array($sCode,self::$arrbarCodeFilter)){
			
				$desProductLine =$pd->getAposDes($sCode);
				if(!empty($desProductLine)){
					
					$weeklyOrder->initalorder($noOrder, $shop, $dateOrder, $sCode,$wk1Sales, $wk2Sales, $stockShop, $stockWarehouse, $isHot,$orderQty,$maxSold,$desProductLine['DESCRIPT'],2);
				}
			}
			
			}
			
		}
		}
		// Combine Special Order 
		if(!empty($arrWithQtyOrderSpecial)){
		foreach($arrWithQtyOrderSpecial as $k3 => $v3){
			
			$sCode = trim($v3['code_product']);
			$urlStock = "http://".SERVER_IP_COMM."/products/get-current-stock/barcode/".$sCode;
			
			$stockShop = $v3['qty_act'];
			$stockWarehouse = Model_System_Downloadhelper::downloadUrl($urlStock);
			$orderQty = $v3['qty_order'];
			
			$isExist = $weeklyOrder->barcodeExistInOrder($sCode, $noOrder);
			
			if(!$isExist && $orderQty > 0){
				
				$wk1Sales = 0;
				$wk2Sales = 0;
				$isHot = "SPORD";
				$maxSold = 0;
				$desProductLine =$pd->getAposDes($sCode);
				if(!empty($desProductLine)){
					$weeklyOrder->initalorder($noOrder, $shop, $dateOrder, $sCode,$wk1Sales, $wk2Sales, $stockShop, $stockWarehouse, $isHot,$orderQty,$maxSold,$desProductLine['DESCRIPT'],2);
				}
				
			}
				
		}
		}
		
	}
	

	
		if($_POST){
			
			// check if add barcode
			//check barcode in the ordr ?
			// if not inital order
			
			if(isset($_POST['btn_add_code'])){
				
				$sCode = trim($_POST['code_add']);
				
				$isExist = $weeklyOrder->barcodeExistInOrder($sCode, $noOrder);
				
				if(!$isExist){
				
				$stockShop = 0;
				$stockWarehouse = 0;
				
				$wk1Sales = $invPro->getProductSalesQtyByDates($dateBegin, $dateEnd, $sCode);
				$wk2Sales = $invPro->getProductSalesQtyByDates($wk2Begin, $wk2End, $sCode);
				
				//dd($wk1Sales,$wk2Sales);
				
				$isHot = $invPro->isHotItem($sCode);
					
				$stShopLine = $stock->getStockBalance($sCode, self::$arrShopMaping[$shop]);
				$stockShop = ($stShopLine)?$stShopLine['BALANCE']:0;
					
				$stWhLine = $stockWh->getStockBalance($sCode,'WH');
				$stockWarehouse = ($stWhLine)?$stWhLine['BALANCE']:0;
					
				$maxSold = $invPro->maxSoldWeeks($sCode, $dateEnd,4);
				$isNew = $pro->isNewProduct($sCode);
				$isSp = false;
				if(substr($sCode,0,2)=="SP" && substr($sCode,0,7)!="SPEAKER"){
					if($shop == "WBPC" || $shop == "WBIC" || $shop == "EPIC" || $shop == "BSIC" ){
						$isSp = true;
					}
				}
				$orderQty = $invPro->calOrderQty($wk1Sales, $wk2Sales, $stockShop, $isHot,$maxSold,$isNew,$isSp);
				
				$desProductLine =$pd->getAposDes($sCode);
					if(!empty($desProductLine) && $stockWarehouse > 0){
						$weeklyOrder->initalorder($noOrder, $shop, $dateOrder, $sCode,$wk1Sales, $wk2Sales, $stockShop, $stockWarehouse, $isHot,$orderQty,$maxSold,$desProductLine['DESCRIPT'],1);
					}
				}
			}
			 
			
			// check if update Qty
			if(isset($_POST['btn_save']) || isset($_POST['btn_save2'])  ){			
				/*
				foreach($_POST['qty_order'] as $idOrder => $orderQty){
					$weeklyOrder->reviseQty($idOrder, $orderQty);
				}
				*/
				
				foreach($_POST['qty_order_shop'] as $idOrder => $orderQty){
					$weeklyOrder->reviseQtyShop($idOrder, $orderQty);
				}
			}
			
			
			
			
			
		}
		
		
		$orderList = $weeklyOrder->getOrderByNo($noOrder);
		
		//d($orderList);
		
		$this->view->orderList = $orderList;
		
		
		$remoteUrl = "http://".WEB_IP."/products/export-weeks-order/shop/".$shop;
		
		if($isSpecial){
			
			$remoteUrl = "http://".WEB_IP."/products/export-weeks-order/spod/yes/shop/".$shop;
		}
		
		if($_POST && isset($_POST['btn_gen_excel'])){
			echo $res = Model_System_Downloadhelper::downloadUrl($remoteUrl);
			echo "Your Final Order Is Generated";
		}
	}
	/**
	 * Add on 2014-11-14,for Modify weekly sales for shop
	 * This is the version 1 of the page 
	 * this has been replaced by version 2
	 */
	public function modifyWeeksOrderPublicAction(){
		
	}
	/**
	 * Add on 2015-01-05 ,separate table by category 2 order 
	 * this one will using different category to separate the order 
	 */
	public function modifyWeeksOrderV2Action(){
		
		set_time_limit(0);
		
		$shop = $this->_getParam("shop");
		$this->view->shop = $shop;
		$isSpecial = $this->_getParam("spod");
		// Check if it is specail Order
		$isSpecial = ($isSpecial == "yes")?true:false;
		/**
		 * For Product OrDer / Special orDer
		 * PD: Order Date Mondy of the Week, Order for Last week Monday/Sunday
		 * SD: Order Date TODAY, order From lastweek monday to yesterday
		 */
		$errorMessage = "";
		$preFix = "PD";
		
		$datePD = Model_DatetimeHelper::getThisWeekMonday("");
		$dateOrder = Model_DatetimeHelper::getThisWeekMonday();
		
		$dateBegin = Model_DatetimeHelper::getLastWeekMonday();
		$dateEnd = Model_DatetimeHelper::getLastWeekSunday();
		if($isSpecial){
		
			$preFix = "SD"; // special second order
			$datePD = Model_DatetimeHelper::dateToday(""); //thursday order
			$dateOrder = Model_DatetimeHelper::dateToday();
		
			$dateBegin = Model_DatetimeHelper::getLastWeekMonday(); // special order
			$dateEnd = Model_DatetimeHelper::dateYesterday(); // special order
				
		}
			
		// use 2week avarage sales
		$wk2Begin = Model_DatetimeHelper::adjustWeeks("sub", $dateBegin, 1);
		$wk2End = Model_DatetimeHelper::adjustWeeks("sub", $dateEnd, 1);
		
		$weeklyOrder = new Model_DbTable_Order_Weeklyorder();
		$orderSpecial = new Model_Products_Adjustment();
		
		
		$pro = new Model_DbTable_Productsva();
		$orderCate = new Model_Products_Categoryorder();
		
		$this->view->arrOrderCate = $orderCate->listAllArray();
		
		$noOrder = $preFix.$shop.$datePD;
		$this->view->noOrder = $noOrder;
		
		$this->view->isLocked = $weeklyOrder->isLocked($noOrder);
		//d($this->view->isLocked);
		if($_POST){
		
			// check if add barcode
			//check barcode in the ordr ?
			// if not inital order
		
			if(isset($_POST['btn_add_code'])){
		
				$codeList = explode(",", $_POST['code_add']);
				foreach ($codeList as $v){
					if(!empty($v)){
					$sCode = trim(strtoupper($v));
		
				//check if it is multiple item
						
					$isExist = $weeklyOrder->barcodeExistInOrder($sCode, $noOrder);
						
					if(!$isExist){
							
						$stockShop = 0;
						$stockWarehouse = 0;
						
						$desProduct = $pro->getProductByBarcode($sCode);
						
						if(!empty($desProduct)){
							$desProductLine	= $desProduct['title_product'];
							$wk1Sales = Model_System_Downloadhelper::downloadUrl('http://'.SERVER_IP_COMM.'/products/get-product-sales/shop/'.$shop.'/period/w1/barcode/'.$sCode);
							$wk2Sales = Model_System_Downloadhelper::downloadUrl('http://'.SERVER_IP_COMM.'/products/get-product-sales/shop/'.$shop.'/period/w2/barcode/'.$sCode);
		
							//dd($wk1Sales,$wk2Sales);
		
							$isHot = Model_System_Downloadhelper::downloadUrl('http://'.SERVER_IP_COMM.'/products/is-hot-product/shop/'.$shop.'/barcode/'.$sCode);
							$stockShop = Model_System_Downloadhelper::downloadUrl('http://'.SERVER_IP_COMM.'/products/get-current-stock/barcode/'.$sCode.'/shop/'.$shop);
							$stockWarehouse = Model_System_Downloadhelper::downloadUrl('http://'.SERVER_IP_COMM.'/products/get-current-stock/barcode/'.$sCode);		
							$maxSold = Model_System_Downloadhelper::downloadUrl('http://'.SERVER_IP_COMM.'/products/get-product-sales/shop/'.$shop.'/period/max/barcode/'.$sCode);
							$isNew = $pro->isNewProduct($sCode);
							$isSp = false;
							if(substr($sCode,0,2)=="SP" && substr($sCode,0,7)!="SPEAKER"){
								if($shop == "WBPC" || $shop == "WBIC" || $shop == "EPIC" || $shop == "BSIC" ){
									$isSp = true;
								}
							}
							$orderQty = Model_System_Downloadhelper::downloadUrl('http://'.SERVER_IP_COMM.'/products/order-qty/w1/'.trim($wk1Sales).'/w2/'.trim($wk2Sales).'/sk_shop/'.trim($stockShop).'/is_hot/'.trim($isHot).'/max/'.trim($maxSold).'/is_new/'.(int)$isNew.'/is_sp/'.(int)$isSp);
		
								
		
							$weeklyOrder->initalorder($noOrder, $shop, $dateOrder, $sCode,$wk1Sales, $wk2Sales, $stockShop, $stockWarehouse, $isHot,$orderQty,$maxSold,$desProductLine,1);
		
						}
						else{
								
							$errorMessage .= "Barcode :".$sCode." Are Not In Our System, Please Verify The Barcode And Try Again<br />";
								
						}
							
		
					}else{
						$idOrder = $isExist['id_order'];
						$orderQty = $isExist['qty_order_shop'] + 1;
						$weeklyOrder->updateExistQtyShop($idOrder, $orderQty);
					}
					
					
					}
				}
						
		
			}
		
		
			// check if update Qty
			if(isset($_POST['btn_save']) || isset($_POST['btn_save2'])  ){
		
				foreach($_POST['qty_order'] as $idOrder => $orderQty){
					$weeklyOrder->reviseQtyShop($idOrder, $orderQty);
				}
		
			}
		
		
		
		
		
		}
		
		
		$orderList = $weeklyOrder->getOrderByNoByQty($noOrder);
		$orderList = $this->formatOrderByCategory($orderList);
		//d($orderList);
		$this->view->orderList = $orderList;
		
		
		if($_POST && isset($_POST['btn_notify'])){
				
			$mail = new Model_Emailshandler();
			$mail->sendNormalEmail("warehouse1@phonecollection.com.au","Order For Shop ".$shop." Has been Finished","Please Have a Check");
			$errorMessage .= "Email To Warehouse Has Been Sent<br />";
		}
		/*
		
		$tmplist = Model_System_Downloadhelper::downloadUrl('http://'.SERVER_IP_COMM.'/products/get-product-list/shop/'.$shop);
		
		$list = explode(";", $tmplist);
		$optionList = array();
		foreach ($list as $k => $v){
			$exp = explode(",", $v);
			if(!empty($exp[0])){
				$optionList[$exp[0]] = $exp[1];
			}
		}
		$this->view->optionList = $optionList;
		*/
		
		$this->view->errorMsg = $errorMessage;
	}
	/**
	 * After the order is modifed , the version 2 give the staff a summary
	 * what has been changed , if staff confirmed , then submit the order to warehouse 
	 * or it can be modify again
	 */
	public function modifyWeeksOrderSummaryAction(){
		
		$noOrder = $this->_getParam("no_order");
		$shop = $this->_getParam("shop");
		$this->view->shop = $shop;
		$weeklyOrder = new Model_DbTable_Order_Weeklyorder();
		$errorMessage = '';
		
		$orderList = $weeklyOrder->getOrderByNoByQty($noOrder);
		$orderList = $this->formatOrderByCategory($orderList);
		
		//d($orderList);
		$this->view->orderList = $orderList;
		
		$orderCate = new Model_Products_Categoryorder();
		
		$this->view->arrOrderCate = $orderCate->listAllArray();
		
		if($_POST && isset($_POST['btn_notify'])){
		
			$mail = new Model_Emailshandler();
			$mail->sendNormalEmail("warehouse1@phonecollection.com.au","Order For Shop ".$shop." Has been Finished","Please Have a Check");
			$errorMessage .= "Email To Warehouse Has Been Sent, You may Close the Page<br />";
			$weeklyOrder->lockOrder($noOrder);
		}
		
		$this->view->errorMsg = $errorMessage;
	}
	
	/**
	 * This function run on 124 when the order is modifyed and then 
	 * warehouse click the button to export the order into excel format
	 * this function should not working stand alone
	 */
	public function exportWeeksOrderAction(){
		
		$orderBegin = Model_DatetimeHelper::getLastWeekMonday();
		$orderEnd = Model_DatetimeHelper::getLastWeekSunday();
		
		$dateOrder = Model_DatetimeHelper::getThisWeekMonday(); //This monday
		
		
		$isSpecial = $this->_getParam("spod");
		if($isSpecial == 'yes'){
			$orderBegin = Model_DatetimeHelper::getLastWeekMonday();// special order 
			$orderEnd = Model_DatetimeHelper::dateYesterday();
			$dateOrder = Model_DatetimeHelper::dateToday();
		}
		set_time_limit(0);
		$shop = $this->_getParam("shop");
		
	
		// special order 
		$dateExtraOrder = Model_DatetimeHelper::adjustDays("sub",$orderEnd,2); // Last Friday
		
		$orderWeekly = new Model_DbTable_Order_Weeklyorder();
		$orderSold = new Model_DbTable_Products_Stock_Extraorder();
		
		$pro = new Model_DbTable_Productsva();
		$location = new Model_Products_Location();
		
		//get order from weekly order 
		$arrWithQtyOrderWeekly = $orderWeekly->getWithQtyOrder($shop, $dateOrder);
		//$arrWithQtyOrderExtra = $orderSold->getUnhandleExtraOrderWithQty($shop);
		//$arrWithQtyOrderExtra = array();
		//$arrWoQtyOrderWeekly = $orderWeekly->getWithQtyOrder($shop, $dateOrder,'wo');
		//$arrWoQtyOrderExtra = $orderSold->getUnhandleExtraOrderWithQty($shop,'wo');
		//$arrWoQtyOrderExtra = array();
		
		$arrWithQtyCombine = array();
		$arrBarcodeSort = array();
		$arrWithQtyBackOrder = array();
		$arrBarcodeSortBo = array();
		$arrWoQtyCombine = array();
		$arrBarcodeWoSort = array();
		$arrWoQtyBackOrder = array();
		$arrBarcodeSortBoWo = array(); 
		
		
		$orderNo = "";
		
		foreach($arrWithQtyOrderWeekly as $k => $orderWeeklyLine){

				if($k==0){
				$orderNo = $orderWeeklyLine['no_order'];
				}
			if($orderWeeklyLine['stock_wh'] >0){
			// put on order 
				$qtyWh = Model_System_Downloadhelper::downloadUrl('http://'.SERVER_IP_COMM.'/products/get-current-stock/barcode/'.$orderWeeklyLine['code_product']);
				$tmpArr = array();
				$tmpArr[] = $orderWeeklyLine['code_product'];
				$tmpArr[] = substr($orderWeeklyLine['status_hot'],0,3);
				$tmpArr[] = trim($orderWeeklyLine['des_product']);
				$tmpArr[] = $orderWeeklyLine['qty_sales_w1'];
				$tmpArr[] = $orderWeeklyLine['qty_max_sold'];
				$tmpArr[] = $orderWeeklyLine['stock_shop'];
				$tmpArr[] = $qtyWh;
				$tmpArr[] = $orderWeeklyLine['qty_order'];
			
			// introduce date , later change by first sales Date
				$tmpArr[] = $pro->isNewProduct($orderWeeklyLine['code_product']);
			//max sold , qty = 0;
				if( ($orderWeeklyLine['qty_order'] + $orderWeeklyLine['stock_shop']) < $orderWeeklyLine['qty_max_sold'] ){
					$tmpArr[] = true;
				}
				else{
					$tmpArr[] = false;
				}
			//withOrder 
				$tmpArr[] = true;
				$tmpArr[] = $location->getPLByProduct($orderWeeklyLine['code_product']);
				$tmpArr[] =  $orderWeeklyLine['qty_order_shop'];
			
				if($qtyWh >0){
					$arrWithQtyCombine[] = $tmpArr;
					$arrBarcodeSort[]= $orderWeeklyLine['code_product'];
				}
				else{
					$arrWithQtyBackOrder[] = $tmpArr;
					$arrBarcodeSortBo[]= $orderWeeklyLine['code_product'];				
				
				}
			}
		}
		/*
		foreach($arrWithQtyOrderExtra as $k2 => $orderExtraLine){
			
			$tmpArr = array();
			$tmpArr[] = $orderExtraLine['barcode'];
			$tmpArr[] = '---';
			$tmpArr[] = trim($orderExtraLine['description']);
			$tmpArr[] = 'X';
			$tmpArr[] = $orderExtraLine['max_sold'];
			$tmpArr[] = 0;
			$tmpArr[] = "-";
			$tmpArr[] = $orderExtraLine['qty'];

			
			$tmpArr[] = $pro->isNewProduct($orderExtraLine['barcode']);
			$tmpArr[] = false;
			$tmpArr[] = true;
			$tmpArr[] = $location->getPLByProduct($orderExtraLine['barcode']);
			if($isSpecial != "yes"){	
			$arrWithQtyCombine[] = $tmpArr;
			$arrBarcodeSort[]= $orderExtraLine['barcode'];	
			}
		}
		if($isSpecial != "yes"){
			array_multisort($arrBarcodeSort,SORT_ASC,$arrWithQtyCombine);
		}
		
	foreach($arrWoQtyOrderWeekly as $k3 => $orderWeeklyLine){

			// put on order 
			$tmpArr = array();
			$tmpArr[] = $orderWeeklyLine['code_product'];
			$tmpArr[] = substr($orderWeeklyLine['status_hot'],0,3);
			$tmpArr[] = trim($orderWeeklyLine['des_product']);
			$tmpArr[] = $orderWeeklyLine['qty_sales_w1'];
			$tmpArr[] = $orderWeeklyLine['qty_max_sold'];
			$tmpArr[] = $orderWeeklyLine['stock_shop'];
			$tmpArr[] = $orderWeeklyLine['stock_wh'];
			$tmpArr[] = $orderWeeklyLine['qty_order'];
			
			// introduce date , later change by first sales Date
			$tmpArr[] = $pro->isNewProduct($orderWeeklyLine['code_product']);
			//max sold , qty = 0;
			if( ($orderWeeklyLine['qty_order'] + $orderWeeklyLine['stock_shop']) < $orderWeeklyLine['qty_max_sold'] ){
				$tmpArr[] = true;
			}
			else{
				$tmpArr[] = false;
			}
			//withOrder 
			$tmpArr[] = false;
			$tmpArr[] = $location->getPLByProduct($orderWeeklyLine['code_product']);
			if($orderWeeklyLine['stock_wh'] >0){
				$arrWoQtyCombine[] = $tmpArr;
				$arrBarcodeWoSort[]= $orderWeeklyLine['code_product'];
			}
			else{
				$arrWoQtyBackOrder[] = $tmpArr;
				$arrBarcodeSortBoWo[]= $orderWeeklyLine['code_product'];
			}
		}
		
		foreach($arrWoQtyOrderExtra as $k4 => $orderExtraLine){
				
			$tmpArr = array();
			$tmpArr[] = $orderExtraLine['barcode'];
			$tmpArr[] = '---';
			$tmpArr[] = trim($orderExtraLine['description']);
			$tmpArr[] = 'X';
			$tmpArr[] = $orderExtraLine['max_sold'];
			$tmpArr[] = 0;
			$tmpArr[] = "-";
			
			if($orderExtraLine['order_option'] == 1){
				$tmpArr[] = $orderExtraLine['qty'];
			}
			elseif($orderExtraLine['order_option'] == 2 ){
				$tmpArr[] = '?';
			}
			$tmpArr[] = $pro->isNewProduct($orderExtraLine['barcode']);
			$tmpArr[] = false;
			$tmpArr[] = false;
			$tmpArr[] = $location->getPLByProduct($orderExtraLine['barcode']);
			if($isSpecial != "yes"){
			$arrWoQtyCombine[] = $tmpArr;
			$arrBarcodeWoSort[]= $orderExtraLine['barcode'];
			}
		}
		*/
		array_multisort($arrBarcodeWoSort,SORT_ASC,$arrWoQtyCombine);
		array_multisort($arrBarcodeSortBoWo,SORT_ASC,$arrWoQtyBackOrder);
		//echo "<pre>";
		
		//var_dump($arrWithQtyCombine);
		
		//echo "</pre>";
		
		//$arrWithQtyAll = array_merge($arrWithQtyCombine,$arrWithQtyBackOrder);
		
		$arrRes = array_merge($arrWithQtyCombine,$arrWithQtyBackOrder,$arrWoQtyCombine,$arrWoQtyBackOrder);
		//d($arrRes);
		$arrLocationSort = array();
		$arrNoLocation = array();
		$arrPosSort = array();
		
		foreach($arrRes as $key => $v){
			
			if($v[12]!=0){
				
			
				
			if($v[11]=="" ){
				
				$arrNoLocation[] = $v;
			
			}
			else{
				
				//cal location position
				$arrLetters = str_split($v[11]);
				$first = ord($arrLetters[0]);
				$second = 99;
				$last = 99;
				if(isset($arrLetters[1])){
				$second = ($arrLetters[0]=="B" || $arrLetters[0]=="D" ||$arrLetters[0]=="F" || $arrLetters[0]=="H" || $arrLetters[0]=="J" || $arrLetters[0]=="L"
				 || $arrLetters[0]=="N")?(10-(int)$arrLetters[1]):(int)$arrLetters[1];

				$last = (isset($arrLetters[2]))?(int)$arrLetters[2]:0;
				}
				
				
				$position = $first * 10000 + $second * 100 + $last;
				
				$arrPosSort[$key] = $position;
				$arrLocationSort[$key] = $v;
			
			}	
			}		
		}
		
		array_multisort($arrPosSort,SORT_ASC,$arrLocationSort);
		$arrRes = array_merge($arrLocationSort,$arrNoLocation);
				
		//d($arrRes);
		
		$fl = new Model_Fileshandler();
		$webIp = unserialize(WEB_IP);
		
		echo "<br />";
		$exportFileName = "WK_".$shop."_".$orderBegin."_".$orderEnd."_".$orderNo;
		echo "<a href=\"http://".WEB_IP."/export/sales/{$exportFileName}.xls\" >{$exportFileName}.xls</a>";
		$fl->exportWeeklySalesShop($arrRes, $exportFileName);
		
		
		echo "<br />File Out Put Done , ";
		//get order from sold out item
		//barcode , hot , des, last max , onhand , wh, qty
		$sh = new Model_DbTable_Shoplocation();
		$sEmail = $sh->getShopMailByHead($shop);
		$mail = new Model_Emailshandler();
		//d($shop,$sEmail);
		$mail->sendNormalEmail($sEmail,"Your Order Excel File Link is HERE(".$shop.")","Please Check Attached Excel File to Order, You have already Finished the Modification, This is just for your reference"."<br/><br/>"."<a href=\"http://".WEB_IP."/export/sales/{$exportFileName}.xls\" >{$exportFileName}.xls</a>");
		$mail->sendNormalEmail("warehouse1@phonecollection.com.au","Your Order Excel File Link is HERE(".$shop.")","Please Check Excel File to Order"."<br/><br/>"."<a href=\"http://".WEB_IP."/export/sales/{$exportFileName}.xls\" >{$exportFileName}.xls</a>");
		//$mail->sendNormalEmail("eco3@phonecollection.com.au","Your Order Excel File Link is HERE(".$shop.")","Please Check Attached Excel File to Order"."<br/><br/>"."<a href=\"http://".WEB_IP."/export/sales/{$exportFileName}.xls\" >{$exportFileName}.xls</a>");

	}
	/**
	 * After the order is done and pickuped up
	 * then the staff will scan to check the Qty
	 * after Qty is check, The KT csv file will be generated for warehouse staff 
	 * to import into the apos
	 */
	public function generateKtAction(){
		
		$orderNo = $this->_getParam("orderno");
		$shop = $this->_getParam("shop");
		$dateMonday = Model_DatetimeHelper::getThisWeekMonday("");
		
		
		if($orderNo == ""){
			
			$orderNo = "PD".$shop.$dateMonday;
		}
		
		$porder = new Model_DbTable_Order_Weeklyorder(Zend_Registry::get('db_remoteapp'));
		$border = new Model_DbTable_Products_Stock_Extraorder(Zend_Registry::get('db_remoteapp'));
		$pList = $porder->getOrderByNo($orderNo);
		
		// do 2 things 1 , find different 
		
		$arrRes = array();

		foreach($pList as $k => $v){
			$fullfill = $border->checkByBarcodeShop($v['code_product'], $v['shop_code']);
			if($v['act_send'] > 0){
				$arrRes[] = array($v['code_product'],$v['act_send']);
				if($fullfill){
					$border->fullfillOrder($fullfill['id_ext_order']);
				}
				
			}else if($v['qty_order_shop'] > 0 && empty($v['act_send'])){
				if($fullfill){
					$border->updateExtOption($fullfill['id_ext_order'], 1, $v['qty_order_shop'], 110);
				}else{
					$border->addExtraorder($v['code_product'], $v['des_product'], $v['shop_code'], $v['date_order'], $v['stock_wh'],null,null,null,null,1,110);
					
				}
			}
			
			
			
		}
		
		$fileName = "KT_".$orderNo;
		$fl = new Model_Fileshandler();
					
		$fl->exportWeeklyKt($arrRes, $fileName);
		
		echo "KT Generateded Click <a href='/export/kt/{$fileName}.xls' target='_blank' >Here</a> to Download.";
	}
	
		
	/**
	 * API function 
	 * this function run on 126 and get barcode descripton for a product
	 * it only get the old apos product description not the new one
	 */
	public function getOldAposProductDescriptionAction(){
		
		$this->_helper->layout->disableLayout();
		
		$sCode = $this->_getParam('barcode');
		$proDes = Model_Aposinitnew::initProDes();
		$desLine = $proDes->getAposDes(trim($sCode));
		$proDetail = new Model_DbTable_Productsva(Zend_Registry::get('db_remoteapp'));
		$disCheck = $proDetail->getProductByBarcode(trim($sCode));
		$qtyWh = Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/get-current-stock/barcode/".trim($sCode));
		if(!$desLine || ($disCheck['is_disc'] == 1 && $qtyWh <= 0)){
			echo "Item Description Not Available,Please Verify Product Barcode";
		}else{
			echo trim($desLine['DESCRIPT']);
		}

	}
	/**
	 * API function 
	 * this one get and return the serialzed product category 123
	 */
	public function getOldAposProductCategoryAction(){
		$this->_helper->layout->disableLayout();
		$sCode = $this->_getParam('barcode');
		$proDes = Model_Aposinitnew::initProDes();
		$desLine = $proDes->getAposDes(trim($sCode));
		echo serialize(array(trim($desLine['CAT']),trim($desLine['CAT2']),trim($desLine['CAT3'])));
		
	}
	/**
	 * API fucntion 
	 * return the APOS product price A
	 */
	public function getOldAposProductPriceaAction(){
		
		$this->_helper->layout->disableLayout();
		
		$sCode = $this->_getParam('barcode');
		$proDes = Model_Aposinitnew::initProDes();
		$desLine = $proDes->getAposDes(trim($sCode));
		if(!$desLine) echo "9999";
		echo round(trim($desLine['UPRICE']),2);
		
	}
	
	/**
	 * API fucntion 
	 * in APOS there is SCODE and barcode 1 2
	 * this function check the given barcode and try to match
	 * barcode 1 and 2 
	 * if any is found , return the found sCode
	 */
	public function matchAposBcodeAction(){
		
		$this->_helper->layout->disableLayout();
		
		$bCode = $this->_getParam("bcode");
		$proDes = Model_Aposinitnew::initProDes();
		$pLine = $proDes->matchBcode(trim($bCode));
		echo trim($pLine['SCODE']);
	}
	
	/**
	 * This function get the shop analysis result and show to the public on 124
	 */
	
	public function shopAnalysisPublicAction(){
		set_time_limit(0);
		
		$shop = $this->_getParam("shop");
		$url = "http://".SERVER_IP_COMM."/products/shop-analysis/shop/{$shop}";

		$email = $this->_getParam("em");
		if($email=="yes"){
			
			$result = Model_System_Downloadhelper::downloadUrl($url);
			$mail = new Model_Emailshandler();
			$sh = new Model_DbTable_Shoplocation();
			$shopMail = $sh->getShopMailByHead($shop);
			$mail->sendNormalEmail($shopMail,"shop Analysis", $result);
			$mail->sendNormalEmail("eco3@phonecollection.com.au", "Subject", $result);
			echo "Email Send You may close the page";
			
		}else{
			echo $result = Model_System_Downloadhelper::downloadUrl($url);
		}
	}

	/**
	 * This is a private function run on 124 
	 * it run on friday night and send result to 124
	 * if the back order not fullfilled
	 * it marks the back order status accordingly
	 * @param unknown_type $orderOption
	 * @return multitype:
	 */	
	private  function listOrderByOption($orderOption){
		//send on friday night , run on 126 , get result and send by 124
		date_default_timezone_set("Australia/Melbourne");
		
		$extOrder = new Model_DbTable_Products_Stock_Extraorder(Zend_Registry::get('db_remoteapp'));
			
		$proDes = Model_Aposinitnew::initProDes();
		$stockOld =  Model_Aposinitnew::initProBalanceAll();
				
		//1. list all Back order
		
		$arrBackOrder = array();
		
		$boList = $extOrder->getOrderByOption($orderOption);
		
		foreach($boList as $boRow){
			
			if($boRow['oder_fullfill'] ==''){
				
			$key = array_search($boRow['barcode'], $arrBackOrder,true);
				
			if($key!== false){
		
				$arrBackOrder[$key + 1] = $arrBackOrder[$key + 1] + 1;
				$arrBackOrder[$key + 2] .=" , ".$boRow['shop_code'];
				$orgDate = $arrBackOrder[$key + 3];
				$curDate = $boRow['date'];
				if(Model_DatetimeHelper::tranferToInt($curDate) < Model_DatetimeHelper::tranferToInt($orgDate) ){
					
					$arrBackOrder[$key + 3] = $curDate;
				}
			}
			else{
				$arrBackOrder[] = $boRow['barcode'];
				$arrBackOrder[] = 1;
				$arrBackOrder[] = $boRow['shop_code'];
				$arrBackOrder[] = $boRow['date'];
			}
			}	
		}
		$arrBackOrder = array_chunk($arrBackOrder,4);
		$arrBoSort = array();
		foreach($arrBackOrder as $bk => $bv){
		
			$arrBoSort[$bk] = $bv[3];
			$desLine  = $proDes->getAposDes($bv[0]);
			$arrBackOrder[$bk][] = $desLine['DESCRIPT'];
			$stLine = $stockOld->getStockBalance($bv[0],'WH');
			$arrBackOrder[$bk][] = $stLine['BALANCE'];	
		}
		array_multisort($arrBoSort,SORT_DESC,$arrBackOrder);

		return $arrBackOrder;
	}
	
	/**
	 * This is redented function of get old apos product price 
	 */
	
	public function getRrpAction(){
		
		$this->_helper->layout->disableLayout();
		
		$sCode = $this->_getParam("b_code");
		$pro = Model_Aposinitnew::initProDes();
		$PLine = $pro->getAposDes($sCode);
		
		echo $PLine['APRICE'];
		
	}

	/**
	 * this is the public page of online product finder
	 * product finder is run on 126 this one get the result in 126 and
	 * show in 124
	 */
	public function finderPublicAction(){
		
		$shopCode = trim($this->_getParam("shop"));
		
		if($_POST){
			
			
			$url = "http://".SERVER_IP_COMM."/products/finder/barcode/".$_POST['bar_code']."/shop/".$shopCode;
			
			if($shopCode == ""){
				
				$url = "http://".SERVER_IP_COMM."/products/finder/barcode/".$_POST['bar_code'];
			}
			$arrFinder = array(Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::timeNow(),$_POST['bar_code'],($shopCode == "")?"WH":$shopCode);
			$fl = fopen("finderlog.csv","a");
			fputcsv($fl,$arrFinder);
			fclose($fl);
			
			//echo $url."<br />";
			echo $result = Model_System_Downloadhelper::downloadUrl($url);
			
		}
		$this->view->shop = $shopCode;
		
	}
	/**
	 * Product online finder in 126
	 * This one find the barcode , try to find all related product 
	 * if it is not number barcode 
	 * and then show the stock and sales price of the selected shop
	 * if not shop secection it show the warehouse stock 
	 */
	public function finderAction(){
		// remove form last
		$barcode = trim($this->_getParam("barcode"));
		$shopCode = trim($this->_getParam("shop"));
		
		if($shopCode ==""){
			
			$shopCode = "WH";
		}
		
		$proDetail = new Model_Products_Detail(Zend_Registry::get('db_remoteapp'));
		$proDetailLine = $proDetail->getDetailByCode($barcode);
		if($proDetailLine){
			
			$this->view->proDetail = $proDetailLine['description_product'];
		}
		else{
			$this->view->proDetail = "";
		}
		
		//transfer barcode 
		$positionDash = strrpos($barcode,"-");
		$shortBarcode = $barcode;
		if($positionDash > 0){
			$shortBarcode = substr($barcode,0,$positionDash);
		}
		//echo $shortBarcode;
		//list same barcode all colors 
		
		$proDes = Model_Aposinitnew::initProDes();
		
		$colorCode = new Model_DbTable_Barcodecolorcodes(Zend_Registry::get('db_remoteapp'));
		
		
		
		$sList = $proDes->getScodeList($shortBarcode);
		
		$arrRes = array();
		
		foreach($sList as $k => $v){
			
			$tmpArr = array();
			$tmpArr[] = $v['SCODE'];
			$tmpArr[] = $v['DESCRIPT'];
			
			$positionDash = strrpos($v['SCODE'],"-");
			
			if($positionDash > 0 ){
			
			$idColor = str_replace("-", "",substr($v['SCODE'],$positionDash));
			$colorLine = $colorCode->getCode($idColor);
			$tmpArr[] = $colorLine['des_color'];
			$tmpArr[] = $colorLine['hex_code'];
			}
			else{
				
				$tmpArr[] = NULL;
				$tmpArr[] = NULL;
				
			}
			
			
			$arrStock = array();
			foreach(self::$arrShopMaping as $shopK => $shopV){
				$stk = Model_Aposinitnew::initProStock($shopK);
				 $stkLine = $stk->getStockBalance($v['SCODE'], $shopV);
				 $arrStock[$shopK] = $stkLine['BALANCE'];
			}
			$stkWh = Model_Aposinitnew::initProBalanceAll();
			$stkLineWh = $stkWh->getStockBalance($v['SCODE'],'WH');
			$arrStock['WH'] = $stkLineWh['BALANCE'];
			$tmpArr[] = $arrStock;
			$tmpArr[] = $v['APRICE'];
		
			$arrRes[] = $tmpArr;			
		}
		
		$this->view->arrRes = $arrRes;
		$this->view->shop = $shopCode;
		$this->view->barcode = $barcode;
		// get stock 
	
	}
	/**
	 * API function 
	 * api function to get the shot code of the product with out color code
	 * 
	 */
	
	public function finderByShortCodeAction(){
		
		$this->_helper->layout()->disableLayout();
		
		$shortCode = $this->_getParam("shortcode");
		
		$proDes = Model_Aposinitnew::initProDes();
		
		$sList = $proDes->getScodeList($shortCode);
		//d($sList);
		echo $k = base64_encode(serialize($sList));
		
		//d(unserialize(base64_decode($k)));
	}
	
	/**
	 * product editor is every important to ebay and website
	 * it is an individual product detail editor 
	 * it has WYSIWYG editor so the non it staff can copy and edit html
	 * it also able to update the product price 
	 * @author Norman
	 * For eBay /Website put item details in the list 
	 */
	public function productEditorAction(){
		
		//scan barcode first 
		//see if already with details 
		//get answer yes or no 
		// if yes it is update 
		// if not it is insert  (product, product stock, product detail)
		
		$this->view->barcode = $sCode = $this->_getParam("barcode");
	
		//not handling 
		$prova = new Model_DbTable_Productsva();
		$idProduct = $prova->getProductID($sCode);
		
		$positionDash = strrpos($sCode,"-");
		$shortBarcode = $sCode;
		if($positionDash > 0){
			$shortBarcode = substr($sCode,0,$positionDash);
		}
		
		$proDetail = new Model_Products_Detail();
		$flexPriceCate = new Model_DbTable_Products_Price_Flexpricecategory();
		$flexPrice = new Model_DbTable_Products_Price_Flexprice();
		$arrPrice = array();
		$fpList = $flexPriceCate->listAll();
		$this->view->fpList = $fpList;	
		$flexHistory = new Model_DbTable_Products_Price_Flexpricehistory();
		
		
		$pdLine = "";
		if($positionDash >0){
			$pdLine = $proDetail->getDetailByCode($sCode);
			if(!$pdLine){	
			$pdLine = $proDetail->getDetailByShortCode($shortBarcode);		
			$this->view->isNew = true;	
			}
		}
		else{
			$pdLine = $proDetail->getDetailByCode($sCode);
		}
		
		if(!$pdLine){
			$this->view->isNew = true;
		}
		else{
			
			$this->view->pdLine = $pdLine;
		}
		
		
		$proStock = new Model_DbTable_Productstock();
		
		$brand = new Model_DbTable_Barcodemanu();
		$model = New Model_DbTable_Barcodemodel();
		$subType = new Model_DbTable_Barcodeproductsubtype();
		
		$this->view->blist = $bList = $brand->listManu();
		$this->view->mlist = $mList = $model->listAllModel();
		$this->view->slist = $sList = $subType->listAllSubType();
		
		//var_dump($bList);
		if($_POST){
			
			//var_dump($_POST);
			if(isset($_POST['btn_save_price'])){
				//saving price 
				
				foreach($_POST['price'] as $k => $p){
					
					if(trim($p)!="" && $p != $_POST['price_org'][$k] ){
					$flexPrice->conditionalInsert($idProduct, $k, $p, Model_DatetimeHelper::dateToday());
					$flexHistory->addHistory($idProduct, $k, Model_DatetimeHelper::dateToday(), $p);
					}
					}
				$proDetail->lastUpdate($sCode);
			}
			
			if(isset($_POST["scan_barcode"])){
				//first time scan barcode
				$this->_redirect("/products/product-editor/barcode/".$_POST["scan_barcode"]);
				
			}
			else{
				//already have barcode and everything , update details
				if(isset($_POST["btn_add"])){
				// add new product
					// add into new product if 
					$idProduct = $prova->getProductID($sCode);
					if(!$idProduct){					
						$idProduct = $prova->addProduct($sCode,$_POST['apos_title']);
					}
					
					if(!$proStock->idExist($idProduct)){
						$proStock->insertStockWarehouse($idProduct, $_POST['initial_stock']);
					}
					$proDetail->addDetail($idProduct, 
							$_POST['barcode'], 
							$_POST['apos_title'],
							$_POST['mobile_brand'], 
							$_POST['mobile_model'], 
							$_POST['product_category'], 
							$_POST['web_title'],
							$_POST['chinese_title'], 
							$_POST['long_description'],
							null, //, $webpageDescription
							$_POST['product_feature'],
							$_POST['product_demisition'],
							$_POST['product_weight'],
							$_POST['introduce_date'],
							$_POST['url_all_color'],
							$_POST['url_single_color'],
							null, // image zip
							$_POST['supplier_name'],
							$_POST['barcode_supplier'],
							$_POST['ebay_category'],
							$_POST['postage'], 
							$_POST['color']);
					
				}
				if(isset($_POST["btn_update"])){
				// 	update product 
				
					//introduct date 
					$idProduct = $_POST['id_product'];
					
					$proDetail->updateDetail($idProduct,
							$_POST['barcode'], 
							$_POST['apos_title'],
							$_POST['mobile_brand'], 
							$_POST['mobile_model'], 
							$_POST['product_category'], 
							$_POST['web_title'],
							$_POST['chinese_title'], 
							$_POST['long_description'],
							null, //, $webpageDescription
							$_POST['product_feature'],
							$_POST['product_demisition'],
							$_POST['product_weight'],
							$_POST['introduce_date'],
							$_POST['url_all_color'],
							$_POST['url_single_color'],
							null, // image zip
							$_POST['supplier_name'],
							$_POST['barcode_supplier'],
							$_POST['ebay_category'],
							$_POST['postage'], 
							$_POST['color']);
					$proDetail->lastUpdate($_POST['barcode']);
				}
				
				//as long as post check file
				
				
				if(file_exists($_FILES['file_all_color']['tmp_name']) && is_uploaded_file($_FILES['file_all_color']['tmp_name'])) {
					//echo 'No upload';
					$folder = getcwd()."/product_img/home_img/";
					$res = move_uploaded_file($_FILES['file_all_color']['tmp_name'], $folder.trim($_POST['barcode'])."_99.jpg");
					$proDetail->updateImg($_POST['id_product'],trim($_POST['barcode'])."_99.jpg");
				}
			
				if(file_exists($_FILES['file_single_color']['tmp_name']) && is_uploaded_file($_FILES['file_single_color']['tmp_name'])) {
					//echo 'No upload';
					$folder = getcwd()."/product_img/home_img/";
					move_uploaded_file($_FILES['file_single_color']['tmp_name'], $folder.trim($_POST['barcode'])."_0.jpg");
					$proDetail->updateSingleImg($_POST['id_product'],trim($_POST['barcode'])."_0.jpg");
				}
				
				
				$this->_redirect("/products/product-editor/barcode/{$sCode}");
			}
			
			
			
		}
		
		foreach($fpList as $k => $v){
				
			$realPrice = $flexPrice->getPriceByIDCategory($idProduct, $v['id_category']);
			$arrPrice[$v['id_category']] = $realPrice['flex_price'];
		}
		
		$this->view->arrPrice = $arrPrice;
		
		//check barcode in the product, in product detail , if not it is brand new stock , ask apos title and stock 
		// if product exist then only add 
		
		
		
		
	}
	
	/**
	 * API function 
	 * the current stock (ONLINE APOS)
	 * for barcode and shop 
	 * if shop is empty , it will show warehouse stock 
	 */
	public function getCurrentStockAction(){
		
		$this->_helper->layout->disableLayout();
		
		$arrShop = unserialize(ARR_APOS_NEW_SHOP_MAPPING);
		
		$code = $this->_getParam("barcode");
		$shop = $this->_getParam("shop");
		$control = $this->_getParam("rt");
		$stkPro = "";
		if($shop == ""){
			
			$shop = "WH";
			$stkPro = Model_Aposinitnew::initProBalanceAll();
			$stkLineWh = $stkPro->getStockBalance($code,$shop);
			if($control == 1){
				if(!$stkLineWh) {echo "na";}
				else{
					echo (int)$stkLineWh['BALANCE'];
				}
			}	
			else{
			echo (int)$stkLineWh['BALANCE'];			
			}
		}
		else{
			
			$stkPro = Model_Aposinitnew::initProStock($shop);
			$stkLineWh = $stkPro->getStockBalance($code,$arrShop[$shop]);
			echo (int)$stkLineWh['BALANCE'];
			
		}
		


		
	}
	/**
	 * This is unfinished function of new letter to shop staff
	 * it should SHOW Pop up number what is new in our product range 
	 */
	public function newsletterOnlineAction(){
		
		$manu = $this->_getParam("manu");
		$model = $this->_getParam("model");
		$type = $this->_getParam("type");
		
		
		$manus = new Model_DbTable_Barcodemanu();
		$models = new Model_DbTable_Barcodemodel();
		$products = new Model_Products_Detail();
		$arrModelList = array();
		
		if($manu == ""){
			//main page 
			$manuList = $manus->listManu();	
			$this->view->assign("manuList",$manuList);
			
			//d($manuList);
			
			foreach($manuList as $manuName){
				$modelList = $models->listModelByManuCode($manuName['code_barcode']);
				$arrModelList[$manuName['code_barcode']] = $modelList;
				
			}
			$this->view->assign("modelList",$arrModelList);
		}

		//d($manuList,$arrModelList);
		if($manu !="" && $model !="" ){
			// show types 
			//$pList = 
			
		}
		
		
	}

	/**
	 * this is private static function only using in this controller
	 * the barcode filer fiter all the barcode that is not a real product 
	 * or product that we don't care about the stock , which should not be find in any calculation
	 * for example stationary barcode 
	 * @param unknown_type $sCode
	 */
	private static function bCodeFilter($sCode){
				
		$sCode = trim($sCode);
		$sCode3 = substr($sCode,0,3);
		$sCode4 = substr($sCode,0,4);
		$sCode5 = substr($sCode,0,5);
		$sCode7 = substr($sCode,0,7);
		
		$res = false;
		
		if($sCode3 == "ONL" || $sCode4 == "STA-" || $sCode4 == "PC00" || $sCode5 == "STRAP" || $sCode5 == "CREAT" || $sCode5 == "SCI-0" || $sCode7 == "DELITEM" 
			|| $sCode7 == "BATCNOK" || $sCode7 == "BATOMOT" || $sCode7 == "BATONOK" || $sCode7 == "BATOSE-" || $sCode7 == "PCSCREA" || $sCode7 == "VIPGIFT" ||
			$sCode == "CN" ||  $sCode == "INSTALL" || $sCode == "INSTALLATION" || $sCode == "FAULTY" || $sCode == "VOUCHER" || $sCode == "PHONEREPAIR" || 
			$sCode == "SERVICE" || $sCode == "PARTSSALES"){
			
			$res = true;
			}
		
		return $res;
		
	}
	//20140530
	/**
	 * This function will move to online Step 3 
	 */
	public function importFromExcelAction(){}
	/**
	 * product flex price is online price ebay price 
	 * we have flex price table for future e-commerce reason 
	 * this function is made by leo
	 * @author Leo
	 * @version 2014-06-20
	 * New action for show the product flex price, export select data to csv, import and update data via csv file.
	 * 
	 */
	public function productFlexPriceAction(){
		$price = new Model_DbTable_Products_Price_Flexprice(Zend_Registry::get('db_default'));
		$priceHistory = new Model_DbTable_Products_Price_Flexpricehistory(Zend_Registry::get('db_default'));
		$product = new Model_DbTable_Productsva();
		$category = new Model_DbTable_Products_Price_Flexpricecategory();
		$productRrp = new Model_DbTable_Productstock();
		$categoryList = $category->listAll();
		
		$myPlist = array();
		$myPlist2 = array();
		$myPHlist ='';
		$list = $price->listAll();
		$listHistory = $priceHistory->listAll();
		
		foreach($list as $key =>$v){
			$tmpArr = array();
			$tmpArr = $v;
			$categoryName = $category->getCategory($v['id_category']);
			$barcodeDetail = $product->getProduct($v['id_product']);
			$rrpDetail = $productRrp->getStock($v['id_product']);
			$tmpArr['price_rrp'] = $rrpDetail['price_rrp'];
			$tmpArr['code_product'] = $barcodeDetail['code_product'];
			$tmpArr['title_product'] = $barcodeDetail['title_product'];
			$tmpArr['category_name'] = $categoryName['title_category'];
			$myPlist[] = $tmpArr;
		
		}
	
		$this->view->pricelist = $myPlist;	

		if(isset($_POST['export_excel'])){	
			$this->_helper->layout()->disableLayout();
			Kint::enabled(false);
			
			$myCategoryList = array();
			$myTmp = array();
			$csvInput = array();
			$productDetail = array();
			
			$i = 1;
			$y = 1;
			foreach($categoryList as $key => $v){
				$myCategoryList [] = $v['title_category'];
				$myCategoryList [] = 'review_date_'.$i++;
				$myCategoryList [] = 'id_category_'.$y++;
				
			}
			
			$result = array('ID','Barcode','Title','Price_RRP');
			$title = array_merge($result,$myCategoryList);
			$productDetail = $product->listAllProducts();
			
			foreach($productDetail as $k => $value){
				$tmpArr3 = array();
				$tmpArr3 = $value;
				$tmpArr2 = array();
				$test = $price->getPricebyid($value['id_product']);
					if($test!= null){
						
						$rrp = $productRrp->getStock($value['id_product']);
						$tmpArr3['price_rrp'] = $rrp['price_rrp'];
						
						for($i = 1;$i<=count($categoryList);$i++){
								$flexPrice = $price->getFprice($value['id_product'], $i);
					
							if($flexPrice!=null){

									$tmpArr2['id_category'] = $flexPrice['id_category'];
									$tmpArr2['flex_price'] = $flexPrice['flex_price'];
									$tmpArr2['review_date'] = $flexPrice['review_date'];
									$tmpArr3['price_summary'][] = $tmpArr2;
							
							}
						}
							if($tmpArr2!= null){
								$allList[] = $tmpArr3;
							}
					}
			}
	
			$this->renderScript('/products/exportCsv.phtml');
		
			$filename = date('Ymd');
			header("Content-type: text/csv");
			header("Content-Disposition: attachment; filename={$filename}.csv");
			header("Pragma: no-cache");
			header("Expires: 0");
			$outputBuffer = fopen("php://output", 'w');
			
			fputcsv($outputBuffer,$title);

			foreach($allList as $k3 => $val3){
				$myarray = array();
				$myarray['id_product'] = $val3['id_product'];
				$myarray['code_product'] = $val3['code_product'];
				$myarray['title_product'] = $val3['title_product'];
				$myarray['Product_RRP'] = $val3['price_rrp'];
			
				foreach($val3['price_summary'] as $k6 => $v6){
			
					$myarray['PRC_'.$v6['id_category']] = $v6['flex_price'];
					$myarray['review_date'.$v6['id_category']] = $v6['review_date'];
					$myarray['id_category_'.$v6['id_category']] = $v6['id_category'];
				}

				fputcsv($outputBuffer, $myarray);

			}

			fclose($outputBuffer);
		}
		
		
		if(isset($_POST['upload'])){

			if($_POST){
				
				$file = $_FILES['import_excel']['tmp_name'];
				$arrResult = array();
				if(empty ($file)){
					$this->view->errorFlag2 = true;
							
					$this->view->errorMessage = "Please import the file";
					$this->renderScript('/products/importCsv.phtml');
					return false;
				}
				
				$change = 0;
				$arrResult = array();
			
				$fl = fopen($file,"r");
			
				while(($lineData = fgetcsv($fl,0)) != false){
					
					$arrResult[] = $lineData;
				}

			fclose($fl);
			
				date_default_timezone_set('Australia/Melbourne');
				$datechange = date('Y/m/d', time());
				
				for($i=count($arrResult[0])-1;$i>=5;$i-=3){
							$arrayTmp = array();
							$arrayTmp['key_category'] = $i;
							$arrayTmp['key_value'] = $i-2;
					
							$arrayKey[] = $arrayTmp;
					}
				array_shift($arrResult);

					$errorarray = array();
					$error = 0;
			if(isset($_POST['check_box'])){
				$categoryDetail = $category->listAll();
					foreach($arrResult as $k4 => $v4){
						
						if($v4[3]!= 0&& $v4[3]!= null){
								$productRrp->updateProductRrp($v4[0], $v4[3]);
								foreach($categoryDetail as $k5 => $v5){
									if($v5['percentage_price']!= null){
										$price->updateFlexprice($v4[0], $v5['id_category'], $v4[3]*$v5['percentage_price'], $datechange);
										$priceHistory->addHistory($v4[0], $v5['id_category'], $datechange, $v4[3]*$v5['percentage_price']);
									}else{
										$price->updateFlexprice($v4[0], $v5['id_category'], $v4[3]+$v5['detail_price'], $datechange);
										$priceHistory->addHistory($v4[0], $v5['id_category'], $datechange, $v4[3]+$v5['detail_price']);
									}
								}
						}else{

							$priceRrp = $productRrp->getRrpById($v4[0]);
							if($priceRrp['price_rrp']!= 0 && $priceRrp['price_rrp']!= null){
								foreach($categoryDetail as $k5 => $v5){
									if($v5['percentage_price']!= null){
										$price->updateFlexprice($v4[0], $v5['id_category'], $priceRrp['price_rrp']*$v5['percentage_price'], $datechange);
										$priceHistory->addHistory($v4[0], $v5['id_category'], $datechange, $priceRrp['price_rrp']*$v5['percentage_price']);
									}else{
										$price->updateFlexprice($v4[0], $v5['id_category'], $priceRrp['price_rrp']+$v5['detail_price'], $datechange);
										$priceHistory->addHistory($v4[0], $v5['id_category'], $datechange, $priceRrp['price_rrp']+$v5['detail_price']);
									}
								}
							}
						}
					}
					$change = 1;
			}else{

				foreach($arrResult as $key4 => $value4){
						
						foreach($arrayKey as $key5 => $value5){
							if($value4[$value5['key_category']]!= null){
								$oldPrice = $price->getFprice($value4[0], $value4[$value5['key_category']]);
								
								if($value4[$value5['key_value']]!=0){
									if($oldPrice!= false){
										if($oldPrice['flex_price']!= $value4[$value5['key_value']]&&$oldPrice['id_category']==$value4[$value5['key_category']]){

											$price->updateFlexprice($value4[0], $value4[$value5['key_category']], $value4[$value5['key_value']], $datechange);
											$priceHistory->addHistory($value4[0], $value4[$value5['key_category']], $datechange, $value4[$value5['key_value']]);
											
										}
										
									}
									elseif($oldPrice==false&&$value4[$value5['key_value']]!=null&&$value4[$value5['key_category']]!=null){
											$price->addFprice($value4[0], $value4[$value5['key_category']], $value4[$value5['key_value']], $datechange);
									}else{
										$this->view->errorFlag2 = true;
										
										$this->view->errorMessage = "Upload Fail, Miss Categegory";
										$this->renderScript('/products/importCsv.phtml');
										return false;
									}
						
								}else{
									$error++;
									$tmperray = array();
									
									$catName = $category->getCategory($value4[$value5['key_category']]);
									$tmperray['item_id'] = $value4[0];
									$tmperray['item_barcode'] = $value4[1];
									$tmperray['item_title'] = $value4[2];
									$tmperray['item_category'] = $value4[$value5['key_category']];
									$tmperray['category_name'] = $catName['title_category'];
									$errorarray [] = $tmperray;

								}
							}
						}
					
						$change = 1;
				}

				if($error!=0){
					$this->view->errorFlag2 = true;
					$this->view->errorMessage = $errorarray;
					$this->renderScript('/products/importCsv.phtml');
					return false;
				}
			
			}
				if($change!=0){
					$this->renderScript('/products/importCsv.phtml');
				}else{
					$this->view->errorFlag2 = true;
					$this->view->errorMessage = "Upload Fail please try again";
					$this->renderScript('/products/importCsv.phtml');
				}
			}
		}
		if(isset($_POST['export_select_excel'])){
			$this->_helper->layout()->disableLayout();
			//Kint::enabled(false);
			$postArray = array();
			foreach($_POST['checkbox'] as $k => $v){
				
				$tmpArr = array();
				$tmpArr['id_product'] = $_POST['id_product'][$k];
				$tmpArr['id_category'] = $_POST['id_category'][$k];
				$postArray [] = $tmpArr;
			}

			$myCategoryList = array();
			$myTmp = array();
			$csvInput = array();

				
			$i = 1;
			$y = 1;
			foreach($categoryList as $key => $v){
				$myCategoryList [] = $v['title_category'];
				$myCategoryList [] = 'review_date_'.$i++;
				$myCategoryList [] = 'id_category_'.$y++;
			
			}
			//d($myCategoryList);
			$result = array('ID','Barcode','Title','Price_RRP');
			$title = array_merge($result,$myCategoryList);
			//d($title);
			
			foreach($postArray as $k => $value){
				$tmpArr3 = array();
				$tmpArr2 = array();
				$test = $price->getFprice($value['id_product'], $value['id_category']);
				if($test!= null){
			
					$rrp = $productRrp->getStock($value['id_product']);
					$productInfo = $product->getProduct($value['id_product']);
					
					$tmpArr3['id_product'] = $value['id_product'];
					$tmpArr3['code_product'] = $productInfo['code_product'];
					$tmpArr3['title_product'] = $productInfo['title_product'];
					$tmpArr3['price_rrp'] = $rrp['price_rrp'];
					$tmpArr2['id_category'] = $value['id_category'];
					$tmpArr2['flex_price'] = $test['flex_price'];
					$tmpArr2['review_date'] = $test['review_date'];
					$tmpArr3['price_summary'][] = $tmpArr2;

					if($tmpArr2!= null){
						$allList[] = $tmpArr3;
					}
				}
			}
			//d($allList);
			$finalList = array();
			foreach($allList as $key => $val){
					$finalList[$val['id_product']]['id_product'] = $val['id_product'];
					$finalList[$val['id_product']]['code_product'] = $val['code_product'];
					$finalList[$val['id_product']]['title_product'] = $val['title_product'];
					$finalList[$val['id_product']]['price_rrp'] = $val['price_rrp'];
					$finalList[$val['id_product']]['price_summary'][] = $val['price_summary'][0];
			}
			sort($finalList);
			//d($finalList);
			
			$this->renderScript('/products/exportCsv.phtml');
			
			$filename = date('Ymd');
			header("Content-type: text/csv");
			header("Content-Disposition: attachment; filename={$filename}.csv");
			header("Pragma: no-cache");
			header("Expires: 0");
			$outputBuffer = fopen("php://output", 'w');
				
			fputcsv($outputBuffer,$title);
			
		
			foreach($finalList as $key2 => $val2){
				$myarray = array();
				$myarray['id_product'] = $val2['id_product'];
				$myarray['code_product'] = $val2['code_product'];
				$myarray['title_product'] = $val2['title_product'];
				$myarray['Product_RRP'] = $val2['price_rrp'];
				for($x = 1;$x<= count($categoryList); $x++){
						foreach($val2['price_summary'] as $key3 => $val3){
					
						if($val3['id_category'] == $x){
							$myarray['PRC_'.$val3['id_category']] = $val3['flex_price'];
							$myarray['review_date'.$val3['id_category']] = $val3['review_date'];
							$myarray['id_category_'.$val3['id_category']] = $val3['id_category'];
						}
						elseif($val3['id_category'] != $x && count($val2['price_summary']) != count($categoryList)){
							$myarray['PRC_'.$x] = '';
							$myarray['review_date'.$x] = '';
							$myarray['id_category_'.$x] = '';
						}
					}
				
				}
				fputcsv($outputBuffer, $myarray);
			
			}
			
	
		}
	}
	
	
	/**
	 * this function is made by leo 
	 * This function is for add category for e-commerce
	 * auto add flex price base on percentage/exactly price of RRP
	 * @author Leo
	 * @version 2014-07-07
	 * New action for add Flex price category
	 */
	
	public function addFlexCategoryAction(){ 
		$price = new Model_DbTable_Products_Price_Flexprice();
		$category = new Model_DbTable_Products_Price_Flexpricecategory();
		$product = new Model_DbTable_Productstock();
		
		
		$flexPrice = $price->listAll();
		date_default_timezone_set('Australia/Melbourne');
		$datechange = date('Y/m/d', time());
		
		
		if(isset($_POST['submit'])){
			//$category->addCategory($_POST['category_title'],$datechange,$_POST['category_percentage'],$_POST['category_price']);
			$categoryDetail = $category->getCategoryByName($_POST['category_title']);

			foreach($flexPrice as $k => $v){
				$productDetail = $product->getStock($v['id_product']); //get RRP
				$tmpPrice = 0;
				if($categoryDetail['percentage_price']!=null){
					$tmpPrice = $productDetail['price_rrp']* $categoryDetail['percentage_price'];
					//$price->addFprice($v['id_product'], $categoryDetail['id_category'], $tmpPrice , $datechange);
				}elseif($categoryDetail['detail_price']!=null){
					$tmpPrice = $productDetail['price_rrp'] + $categoryDetail['detail_price'];
					//$price->addFprice($v['id_product'], $categoryDetail['id_category'], $tmpPrice , $datechange);
				}else{
					//$price->addFprice($v['id_product'], $categoryDetail['id_category'], $productDetail['PRICE_RRP'] , $datechange);
				}
			}
		}
		
		
		
	}
		
	/**
	 * This is the function run on online controller step 5
	 * the actual page do the job is here 
	 * it get the product detail and price 
	 * then generate the csv file fit the prestashop (phone collection)
	 */
	public function generatePrestaShopCsvAction(){
		
		$codeProduct = strtoupper(trim($this->_getParam("code_product")));
		$shopName = $this->_getParam("shop");
		
		 
				
		$pGen = new Model_Prestagenerator();
		$pDetail = new Model_Products_Detail();
		$pPrice = new Model_DbTable_Products_Price_Flexprice();
		$pdLine = $pDetail->getDetailByCode($codeProduct);
		
		$supplier =$pdLine['name_supplier'];
		$titleProduct = '';
		$price = 999;
		$taxRuleID = 1;
		
		
		$onlineOnly = 0;
		$supplierID = '';
		$qty = 0;
		$rrp = 0;
		$idCategory = 0;
		
		
		if(stripos($supplier,"x-doria")!== false){
			//d($supplier);
			$onlineOnly = 1;
			$supplierID = 1;
			$qty = 3;
			$rrp = 0; // phone collection price 
			$fPrice = $pPrice->getPriceByIDCategory($pdLine['id_product'],2);
			$rrp = $fPrice['flex_price'];
			
			
			if($shopName == "phonecollection"){
				
				$idCategory = '1|456|81'; // iphone 6 category id need to mapping 
			}
		if($shopName == "lovebargain"){
				
				$idCategory = '1'; // iphone 6 category id need to mapping 
			}
			
		}
		if(stripos($supplier,"phonecollection")!== false || $supplier == ''){
				
			$onlineOnly = 0;
			$supplierID = 0;
			$rrp = Model_System_Downloadhelper::downloadUrl('http://'.SERVER_IP_COMM.'/products/get-old-apos-product-pricea/barcode/'.$codeProduct);
			
			$qty = Model_System_Downloadhelper::downloadUrl('http://'.SERVER_IP_COMM.'/products/get-current-stock/barcode/'.$codeProduct);
		}
		
		
		
		
		
		$shortDes =  $pdLine['short_description_product'];
		$longDes = $pdLine['description_product'];
		
		/**
		 * start the image links 
		 * 0,1,2,-> 99
		 */
		$imgUrl = '';
		$imgBaseUrl = '';
		
		
		
		
		if($shopName == "phonecollection"){
		
			
			$titleProduct = $pdLine['apos_title_product']; // use apos title
			$price = $rrp;
				//$shortDes = 	
			$imgBaseUrl = 'http://www.phonecollection.com.au/product_img/home_img/';
			
			
		}
		if($shopName == "lovebargain"){
			$titleProduct = $pdLine['short_description_product']; // using ebay title at the moment 
			$imgBaseUrl = 'http://www.lovebargain.com.au/product_img/home_img/';
		}
		
		$imgUrl .= $imgBaseUrl.$pdLine['img_individual_url']."|";
		
		$shortImgInd = substr($pdLine['img_individual_url'],0,-5);
		$strImg1 = $shortImgInd.'1.jpg';
		$strImg2 = $shortImgInd.'2.jpg';
		
		$imgFolder = getcwd().'/product_img/home_img/';
		
		if(file_exists($imgFolder.$strImg1)){
				
			$imgUrl.=$imgBaseUrl.$strImg1."|";
		}
		
		if(file_exists($imgFolder.$strImg2)){
				
			$imgUrl.=$imgBaseUrl.$strImg2."|";
		}
			
		$imgUrl .= $imgBaseUrl.$pdLine['img_url'];
			
		$pGen->generatePrestaFile($titleProduct, $idCategory, $price, $taxRuleID, $codeProduct,$codeProduct, $supplierID, $pdLine['weight_kg'], $qty, $shortDes, $longDes, $imgUrl, $onlineOnly, $shopName);
		
	}
	/**
	 * This is functon on online controller step 5
	 * this is the actual page who gather all the data and generate the ebay
	 * file exachange format csv 
	 */
	
	public function generateEbayListingAction(){
		
		$codeProduct = $this->_getParam("code_product");
		
		$eBayGenerator = new Model_Ebaygenerator();
		
		$price = new Model_DbTable_Products_Price_Flexprice();
		
		
		
		
		$errorFlag = false;
		// find barcode
		$pDetail = new Model_Products_Detail();
		
		
		
		$pdLine = $pDetail->getDetailByCode($codeProduct);
		//dd($pdLine,$codeProduct);
		// define file today 
		
		$arrFileName = Model_Ebaygenerator::prepareEbayFile();
		
		// check image ready
		// check if local image is ready 
		// check if remote image is ready 
		// Assum Image is ready 
		
		
		//d($pdLine);
		
		$templateStr = $eBayGenerator->prepareTemplate();
		$storeCategory = 0;
		
		$qtyWh = Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/get-current-stock/barcode/".$codeProduct);
		echo "WH Stock".$qtyWh;
		$qty = ($qtyWh/2 > 1)?round($qtyWh/2,0):1; // get stock from apos (in warehouse)
		// ebay price now is lovebargain price 
		if($qty >1){$qty = 3;}
		
		$idProduct = $pdLine['id_product'];
		
		$idCategory = 3; // lovebargain price 
		
		$priceLine = $price->getPriceByIDCategory($idProduct, $idCategory);
		
		$ebayPrice = $priceLine['flex_price'];
		//d($priceLine);
		
		$paypalAccount = 'kmobileau@gmail.com';
		
		$arrLine = $eBayGenerator->generateEbayCsv($pdLine['short_description_product'],
				 $codeProduct,
				 $pdLine['ebay_category'], 
				 $storeCategory, 
				 $qty, 
				 $ebayPrice, 
				 $pdLine['description_product'],
				 "http://www.lovebargain.com.au/product_img/home_img/".$pdLine['img_individual_url'], // No image at moment  
				 "http://www.lovebargain.com.au/product_img/home_img/".$pdLine['img_url'],// no whole image  
				 $paypalAccount, 
				 $pdLine['postage_price'], 
				 $pdLine['feature'], 
				 $pdLine['size_mm'], 
				 $pdLine['weight_kg'], 
				 $templateStr);
		
		 $fl = fopen($arrFileName[0].$arrFileName[1],"a");
		 fputcsv($fl, $arrLine);
		 fclose($fl);
		
		// check information ready 
		
		echo "Done For ".$codeProduct;
		
		
		
		// if all ok then begin to produce
		
		
		
	}
	/**
	 * This function is made by leo
	 * For add and check equipment record
	 * @version 2014-07-30
	 * @author Leo
	 */
	public function equipmentRecordAction(){
		$equipment = new Model_DbTable_Equipmentrecord();
		$stfDetail = new Model_DbTable_Roster_Stafflogindetail();
		$list = $equipment->listAll();
		date_default_timezone_set('Australia/Melbourne');
		$date = date("Y-m-d H:i");
		
		$this->view->list = $list;
		if($_POST){
				$barcode = $_POST['barcode'];
				$des = Model_System_Downloadhelper::downloadUrl("http://".WEB_IP."/products/get-equipment/barcode/".$barcode);
			
				if(trim($des) == 'Equipment Description Not Available,Please Verify Barcode'){
					$isNew = true;
					$arrDes = "";
				}else{
					$arrDes = explode(":", trim($des));
					$isNew = false;

				}
				$this->view->barcode = $barcode;
			
			
			if(!empty($_POST['password'])){
				$barcode = $_POST['barcode'];
				$eqname = $_POST['equipment_name'];
				$modelNo = $_POST['model_no'];
				$snNo = $_POST['sn_no'];
				$shop = $_POST['receiver'];
				$reason = $_POST['reason'];
				$password = $_POST['password'];
				$stfCheck = $stfDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha(trim($password)));
	
				if($stfCheck){
					$equipment->addRecord($barcode,$eqname,$modelNo, $snNo, $shop, 'output', $reason, $date,$stfCheck['id']);
					$url = "http://".WEB_IP."/products/equipment-record";
					$this->_redirect($url);
				}else{
					echo '<script>alert("Wrong Password!!");</script>';
				}
				
				
			}
			$this->view->isNew = $isNew;
			if(!empty($arrDes)){
				$this->view->arrDes = $arrDes;
			}
		}
	}
	
	/**
	 * This function is for after equipment assgin to shop/person
	 * The receiver input password to confirm equipment received
	 @author Leo
	 */
	public function equipmentReceivedAction(){
		$eq = new Model_Products_Equipment();
		$eqRecord = new Model_DbTable_Equipmentrecord();
		$stfDetail = new Model_DbTable_Roster_Stafflogindetail();
		$dateToday = Model_DatetimeHelper::dateToday();
		$id = $this->_getParam('id');
		$shopManager = unserialize(ARR_MANAGER);
		$pendCase = array();
		$this->view->id = $id;
		if($id){
			$pendCase = $eqRecord->listAllById($id);
			//d($shopManager);
			if(array_key_exists($id,$shopManager)){
				foreach($shopManager[$id] as $shop){
					
					$tmpArr = $eqRecord->listAllById($shop);
					
					if($tmpArr){
						foreach ($tmpArr as $k => $v){
							$pendCase[] = $v;
						}
					}

				}
			}
			
			$this->view->pendCase = $pendCase;
		}
		
		if(isset($_POST['submit'])){
			$password = $_POST['password'];
			$idCheck = $stfDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha(trim($password)));
			
				if($idCheck){
					$url = "/products/equipment-received/id/".$idCheck['id'];
					$this->_redirect($url);
				}else{
					echo '<script>alert("Wrong Password");</script>';
				}
			
		}
		
		if(isset($_POST['confirm'])){
			
			if($_POST['checkbox']){
				
				foreach ($_POST['checkbox'] as $k2 => $v2){
					$barcode = $eqRecord->getRecord($k2);
					$eqRecord->confirmReceived($k2,$dateToday);
					$eq->updateLocation($barcode['barcode'], $v2);
				}
			}
			
		}
		
		
	}
	
	/**
	 * This function is for scan property into database
	 * if it exist ,update info
	 * @author Leo
	 * @version 2014-12-24
	 */
	public function addEquipmentInfoAction(){
		$equipment = new Model_Products_Equipment();
		
		if($_POST){
			$barcode = $_POST['barcode'];
			$checkComputer = strpos($barcode,'COMPUTER');
			$checkMonitor = strpos($barcode,'MONITOR');
			$checkDvr = strpos($barcode,'DVR');
			$checkTool = strpos($barcode,'TOOL');
			$checkOther = strpos($barcode,'OTHER');
			
			$des = Model_System_Downloadhelper::downloadUrl("http://".WEB_IP."/products/get-equipment/barcode/".$barcode);
				
			if(trim($des) == 'Equipment Description Not Available,Please Verify Barcode'){
				if($checkComputer !== false){
					$this->view->desc = "Computer";
					$this->view->type = "COMPUTER";
				}elseif($checkMonitor !== false){
					$this->view->desc = "Monitor";
					$this->view->type = "MONITOR";
				}elseif($checkDvr !== false){
					$this->view->desc = "DVR";
					$this->view->type = "DVR";
				}elseif($checkTool !== false){
					$this->view->desc = "Tool";
					$this->view->type = "TOOL";
				}elseif($checkOther !== false){
					$this->view->desc = "Other";
					$this->view->type = "OTHER";
				}elseif(strlen($barcode) == 15){
					$this->view->desc = "Mobel In WH";
					$this->view->type = "Mobel";
					$this->view->model = $barcode;
					$this->view->sn = $barcode;
				
				}else{
					$this->view->added = "1";
				}
				echo "New Product";

			}else{
				$arrDes = explode(":", trim($des));
				$this->view->desc = $arrDes[0];
				$this->view->type = $arrDes[3];
				$this->view->sn = $arrDes[1];
				$this->view->model = $arrDes[2];
				echo '<script>alert("Record Already Exist! ");</script>';
			}

			
			
			
			if(!empty($_POST['sn_no']) && !empty($_POST['model_no'])){
				$exist = $equipment->getByBarcode($barcode);
				if($exist){
					$equipment->updateEquipment($_POST['type'], $barcode, $_POST['desc'], $_POST['sn_no'], $_POST['model_no']);
				}else{
					$equipment->addEquipment($_POST['type'], $barcode, $_POST['desc'], $_POST['sn_no'], $_POST['model_no']);
				}
				$this->view->added = "1";
				
				echo "Add Success<br/>"."Barcode:".$barcode."<br/>Type:".$_POST['type']."<br/>Desc:".$_POST['desc']."<br/>S/N:".$_POST['sn_no']."<br/>Model No:".$_POST['model_no'];
			}
			
			$this->view->barcode = $barcode;
		}
	}
	
	/**
	 * This is the second step of online order 
	 * it also call special order 
	 * since we already stop the stock take 
	 * if the qty difference is found by the staff then they should adjust here 
	 * then KA will be generated next week
	 * however , this function is currently stoped 
	 * Adjust Whatever Qty they want to adjust 
	 * special order has  3 conditions
	 * 
	 * 1. no order just adjusting 
	 * 2. no adjust just want sepcial order 
	 * 3. adjusting and since adjusted , need to order 
	 * 
	 * @auther norman
	 * @verson 2014-08-07
	 * 
	 */
	public function qtyAdjustSuggestionAction(){
		
		$shop = $this->_getParam("shop");
		$dateToday = Model_DatetimeHelper::dateToday();
		
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		
		
		$des = "";
		$shopStock = "";
		$codeProduct = "";
		
		$adj = new Model_Products_Adjustment();

		if($_POST){
			
			// find the product 
			if(isset($_POST['btn_find'])){
				$codeProduct = trim($_POST['code_product']);
				
				$urlDes = "http://".SERVER_IP_COMM."/products/get-old-apos-product-description/barcode/".$codeProduct;
				$urlStock = "http://".SERVER_IP_COMM."/products/get-current-stock/shop/".$shop."/barcode/".$codeProduct;
				
				$des = Model_System_Downloadhelper::downloadUrl($urlDes);
				$shopStock = Model_System_Downloadhelper::downloadUrl($urlStock);
				
			}	
			// add product to the list
			if(isset($_POST['btn_add'])){
				$codeProduct = trim($_POST['code_product']);
				$adj->initAdjustment($shop, $codeProduct, $_POST['qty_apos'],$_POST['qty_act'], $_POST['qty_act'] - $_POST['qty_apos'],$_POST['qty_order'],Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::timeNow());
				
				
			}
			// revise list (manager only)
			if(isset($_POST['btn_revise'])){
				
				$idStaff = $stDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha($_POST['mgr_pass']));
				if($idStaff){
					//check if it mgr 
					$stLine = $stInfo->getStaffinfo($idStaff['id']);
				
					if($stLine['position_status'] == 4 || $stLine['position_status'] == 5 || $stLine['position_status'] == 6 || $stLine['position_status'] == 7   ){
						
						if(isset($_POST['cb_rm'])){
						foreach($_POST['cb_rm'] as $key => $v){
							//d($key);
						$adj->cancelAdjustment($key,$idStaff['id'],Model_DatetimeHelper::dateToday());
						}
						}
						if(isset($_POST['cb_change'])){
						foreach($_POST['cb_change'] as $k => $v){
							
							$adj->updateOrderQty($k, $_POST['qty_order'][$k]);
						}
						}
					}	
				
					
				}
				else{
					
					echo "<h1>Wrong Password!!</h1>";
				}
			}
		}
		
		
		$aList = $adj->listPendingAdjustment($shop,"2014-01-01", $dateToday);
		$cList = $adj->listConfirmAdjustment($shop,"2014-01-01", $dateToday);
		
		$this->view->aList = $aList;
		$this->view->cList = $cList;
		
		$this->view->des = $des;
		$this->view->shopStock = $shopStock;
		$this->view->codeProduct = $codeProduct;
		$this->view->shop = $shop;
		
		//$list = $adj->listAllTempKa();
		//d($list);
		
	}
	/**
	 * This is part of special order 
	 * Freeze Adj Happen on Monday Midnight 
	 * FreeZe and prepare the PD number , ignore the SD
	 */
	public function freezeAdjAction(){
		
		$shop = $this->_getParam("shop");
		//get all pending list , export excel , together with stock lost 
		//on tuesdaday -> mark te
		$tempKa = "TMPA".$shop.Model_DatetimeHelper::getThisWeekMonday('');
		$orderNo = "PD".$shop.Model_DatetimeHelper::getThisWeekMonday('');
		
		
		$adj = new Model_Products_Adjustment();
		$aList = $adj->listPendingAdjustment($shop,"2014-01-01",Model_DatetimeHelper::dateToday());
		foreach($aList as $key => $v){
			//d($key,$v);
			$adj->updateTempKa($v['id_adjust'], $tempKa,$orderNo);
		}	
	}
	
	
	
	public function freezeCycleAction(){
		
		$shop = unserialize(ARR_SHOP);
		foreach($shop as $shopCode){
			
			$str = Model_System_Downloadhelper::downloadUrl("http://".WEB_IP."/products/freeze-adj/shop/".$shopCode);
			
		}
		
		
	}
	/**
	 * This is the function which actually export the KA
	 */
	public function exportAdjSuggestionAction(){
		
		$this->_helper->layout()->disableLayout();
		//happen on tuesday, give list of export , then when 
		//KA number filled , mark all ka to this no.
		$shop = $this->_getParam("shop");
		$adj = new Model_Products_Adjustment();
		
		$l = $adj->listAllTempKa();
	
		echo base64_encode(serialize($l));
		//pendding to the file 
		
	}
	/**
	 * When there is a KA, KT update this week adjustment for this shop
	 */	
	public function updateAdjSuggestionAction(){
		$shop = $this->_getParam("shop");
		$kno = $this->_getParam("no");
		
		$tmpAdj = new Model_Products_Adjustment(Zend_Registry::get('db_remoteapp'));
		$tmpList = $tmpAdj->listTempKaByShop($shop);
		
		$arrShopMapping = unserialize(ARR_APOS_NEW_SHOP_MAPPING);
		
		$ktData ="";
		$kaData = "";
		
		
		if(substr($kno,0,2)=="KT"){
			$ktData = Model_Aposinitnew::initKtData($shop);	
			
			foreach($tmpList as $item){
			
				
				if($ktData->sCodeExist(strtoupper(trim($item['code_product'])), $kno, $arrShopMapping[$shop])){
					$tmpAdj->updateOrderNo($item['id_adjust'], $kno);
				}
				
				
			}
			
		}
		
		if(substr($kno,0,2)=="KA"){
			$kaData = Model_Aposinitnew::initKaData($shop);
			
			foreach($tmpList as $item){
				if($kaData->sCodeExist(strtoupper(trim($item['code_product'])), $kno, $arrShopMapping[$shop])){
					$tmpAdj->updateKaNo($item['id_adjust'], $kno);
				}
			}
		}
		
		//$ktNote =	
	}
	/**
	 * This provide the summary for special order 
	 */
	public function adjustmentSpecialOrderSummaryAction(){
		
		//get summary of Last week , choose everything freezed this monday
		$adj = new Model_Products_Adjustment();
		
		$arrShop = unserialize(ARR_SHOP);
		$dateFreeze = Model_DatetimeHelper::getThisWeekMonday();
		$pros = new Model_DbTable_Productsva();
		$extOrder = new Model_DbTable_Products_Stock_Extraorder();
		
		
		
		if($_POST){
			
			foreach($_POST['choice'] as $k => $item){
				$choice = explode("|", $item);
				
				if($choice[0] == 1){
					//discoutinue
					d($choice);
					$pros->discontinueProducts($choice[1]);
					$adj->updateOrderNo($k,"DISCONTINUED");
				}	
				if($choice[0] == 2){
					// cancel it and  put into back order 
					$adj->cancelAdjustment($k,110,Model_DatetimeHelper::dateToday());
					$adj->updateOrderNo($k,"BACK ORDERED");
					$itemLine = $adj->getAdjustment($k);
					$des = Model_System_Downloadhelper::downloadUrl('http://'.SERVER_IP_COMM.'/products/get-old-apos-product-description/barcode/'.strtoupper($choice[1]));
					$qtyWarehouse = Model_System_Downloadhelper::downloadUrl('http://'.SERVER_IP_COMM.'/products/get-current-stock/barcode/'.strtoupper($choice[1]));					
					$extOrder->addExtraorder(trim($choice[1]), $des, $itemLine['code_shop'],Model_DatetimeHelper::dateToday(), $qtyWarehouse,$itemLine['qty_order'],null,'Special Order to Back Order', 0, 1, 110);
				}
			}
		}
		
		$arrRes = array();
		
		foreach ($arrShop as $shop){
			
			$arrRes[$shop] = $adj->allFreezedThisWeek($dateFreeze, $shop);
			
		}
		
		$this->view->arrRes = $arrRes;
		
		//d($arrRes);
		
	}
	
	
	/**
	 * The following section is for show online invoice for 6 monthes
	 * This fucntion is on the company info page 
	 * this is the actual page run on 126
	 */
	//This is for 126 actual exe
	public function onlineInvoiceAction(){
		
		$shop = $this->_getParam("shop");
		$invoiceNo = $this->_getParam("inv");
		
		$payType = Model_Aposinitnew::initPaytype($shop);
		$this->view->payType = $payType->listAll();
		
		$check = substr($invoiceNo,1,6);
		if($check > '150426'){
		
			$invoice = Model_Aposinitnew::initAposInvoice($shop);
			$invPro = Model_Aposinitnew::initAposInvPro($shop);
		}else{
			$invoice = Model_Aposinit::initAposInvoice($shop);
			$invPro = Model_Aposinit::initAposInvPro($shop);
		}
		$invLine = $invoice->getInvoice($invoiceNo);
		$invProLines = $invPro->getInvoiceProducts($invoiceNo);
		
		//d($invLine,$invProLines,$this->view->payType);
		
		$this->view->invline = $invLine;
		$this->view->invProLines = $invProLines;
			
	}
	// 126 executeable 
	/**
	 * this is the actual page run on 126 generate the list of invoice 
	 * made on that day
	 */
	public function onlineInvoiceListAction(){
		
		$date = $this->_getParam("date");
		$this->view->date = $date;
		$shop = $this->_getParam("shop");
		$dateToday = Model_DatetimeHelper::dateToday();
		$sixMonthMonday = Model_DatetimeHelper::adjustMonths("sub",Model_DatetimeHelper::getFirstDayOfTheMonth($dateToday),6,"");
		
		$date = str_replace('-', '', $date);
		//dd($date);
		if($date < $sixMonthMonday){
			
			echo "<h1> Only Able To Search Invoice With In 6 Monthes </h1>";
		}elseif($date <= '20150426'){
		
			if($date!="" && $shop !="" ){
				$inv = Model_Aposinit::initAposInvoice($shop);
			
				$invList = $inv->getInvoicesByDate($date);
					
				$this->view->invList = $invList;
					
				$this->view->shop = $shop;
			}
		}
		else{
		
			if($date!="" && $shop !="" ){
			$inv = Model_Aposinitnew::initAposInvoice($shop);

			$invList = $inv->getInvoicesByDate($date);
			
			$this->view->invList = $invList;
			
			$this->view->shop = $shop;
			//d($invList);
			}
		}
		
		
		
	}
	
	/**
	 * API function for check refund invoice of shop by date
	 * it is support for cashaccount-manager. no direct link enter 
	 */
	public function onlineRefundListAction(){
		$this->_helper->layout()->disableLayout();
		$shop = $this->_getParam("shop");
		$date = $this->_getParam("date");
		$inv = Model_Aposinitnew::initAposInvoice($shop);
		$invPro = Model_Aposinitnew::initAposInvPro($shop);
		
		$invoice = $inv->getRefundInvoice($date);
		
		$this->view->invList = $invoice;
		$this->view->shop = $shop;
	}
	/**
	 * API Function 
	 * return all the invoice with discount for given dates
	 * this is for check discount poicy using apos
	 * Add by Norman , API level invoice "WITH DISOUNT" array () on 126
	 */
	public function onlineInvoiceListByDateAction(){
		
		$this->_helper->layout()->disableLayout();
		
		$db = $this->_getParam("date_begin");
		$dn = $this->_getParam("date_end");
		
		$shop = $this->_getParam("shop");
		$dis = $this->_getParam("disc");
		
		$arrDate = Model_DatetimeHelper::createDateArray($db, $dn);
		
		$inv = Model_Aposinitnew::initAposInvoice($shop);
	
		$invPro = Model_Aposinitnew::initAposInvPro($shop); 
		$arrRes = array();
		foreach($arrDate as $dateCheck){

			$invList = $inv->getInvoicesByDate($dateCheck);
			
			foreach($invList as $invRow){
				
				if($dis == "yes"){
					$invDis = $inv->ifInvoiceDiscount($invRow['INV_NO']);
					$itemDis = $invPro->ifInvoiceDiscount($invRow['INV_NO']);
					
					if($invDis || $itemDis){
						
						$arrRes[] = $invRow['INV_NO'];
					}
					
					
				}else{
					
					$arrRes[] = $invRow['INV_NO'];
				}	
				
			}
		}
		//d($arrRes);
		echo base64_encode(serialize($arrRes));
	}
	
	/**
	 * API functon , serial lized invoice detail page
	 * Add by Norman , API level invoice array on 126
	 */
	public function onlineInvoiceDetailByIdAction(){
		
		$this->_helper->layout()->disableLayout();
		
		$invNo = $this->_getParam("inv_no");
		$shop = $this->_getParam("shop");
		
		$inv = Model_Aposinitnew::initAposInvoice($shop);
		$invPro = Model_Aposinitnew::initAposInvPro($shop);
		
		$invDetail = $inv->getInvoice($invNo);
		$invProDetail = $invPro->getInvoiceProducts($invNo);
		
		echo base64_encode(serialize(array($invDetail,$invProDetail)));
	}
	
	/**
	 * This is the 124 public presenter let shop staff to check 
	 * the online invoice  
	 */
	public function onlineInvoicePublicAction(){

		$shop = $this->_getParam("shop");
		$invoiceNo = $this->_getParam("inv");
		$dateToday = Model_DatetimeHelper::dateToday();
		$sixMonthMonday = Model_DatetimeHelper::adjustMonths("sub",Model_DatetimeHelper::getFirstDayOfTheMonth($dateToday),6,"");
		
		$invoiceDate = "20".substr($invoiceNo,1,6);
		
		if($invoiceDate >= $sixMonthMonday){
			
			echo Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/online-invoice/shop/".$shop."/inv/".$invoiceNo);
		}
		else{
			echo "<h1> You may only Check Invoice Within 6 Months.</h1>";
		}
	}
	
	public function onlineInvoiceDateAction(){
		$this->_helper->layout->disableLayout();
		$shop = $this->_getParam("shop");
		$inv = $this->_getParam("inv");
		$check = substr($inv,1,6);
		if($check > '150426'){
		
			$invoice = Model_Aposinitnew::initAposInvoice($shop);
			$invPro = Model_Aposinitnew::initAposInvPro($shop);
		}else{
			$invoice = Model_Aposinit::initAposInvoice($shop);
			$invPro = Model_Aposinit::initAposInvPro($shop);
		}
		
		$invLine = $invoice->getInvoice($inv);
		
		if($invLine){
			$date = date('Y-m-d',strtotime($invLine['DATE']));
		}else{
			$date = 0;
		}
		echo $date;
		
	}
	
	/**
	 * this is also the 124 public presenter to list all the invoice for that shop that day
	 */
	public function onlineInvoiceListPublicAction(){
		
		$shop = $this->_getParam("shop");
		$dateToday = Model_DatetimeHelper::dateToday();
		
		$sixMonthMonday = Model_DatetimeHelper::adjustMonths("sub",Model_DatetimeHelper::getFirstDayOfTheMonth($dateToday),6,"");
		
		if($_POST){
				
			$date = $_POST['date'];
			$dateCheck = str_replace('-', '', $date);
			
			if($dateCheck >= $sixMonthMonday){
				echo Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/online-invoice-list/shop/".$shop."/date/".$date);
			}
			else{
				echo "<h1> You may only Check Invoice Within 6 Months.</h1>";
			}
				
			//echo "http://".SERVER_IP_COMM."/products/online-invoice-list/shop/".$shop."/date/".$date;
			
		}
		
		
	}
	/**
	 * This function is for search invoice by date or invoice no.
	 @author Leo
	 */
	public function onlineInvoiceListWhAction(){
		$dateToday = Model_DatetimeHelper::dateToday();
		
		$sixMonthMonday = Model_DatetimeHelper::adjustMonths("sub",Model_DatetimeHelper::getFirstDayOfTheMonth($dateToday),6,"");
		
		if(isset($_POST['button'])){
		
			$date = $_POST['date'];
			$shop = $_POST['shop'];
			$dateCheck = str_replace('-', '', $date);
				
			if($dateCheck >= $sixMonthMonday){
				echo Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/online-invoice-list/shop/".$shop."/date/".$date);
			}
			else{
				echo "<h1> You may only Check Invoice Within 6 Months.</h1>";
			}
		
			//echo "http://".SERVER_IP_COMM."/products/online-invoice-list/shop/".$shop."/date/".$date;
				
		}
		
		if(isset($_POST['search'])){
			$shop = $_POST['shop'];
			$inv = $_POST['invoice'];
			
			$this->view->shop = $shop;
			
			if($shop && $inv){
				echo Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/online-invoice-public/shop/".$shop."/inv/".$inv);
			}
		}
		
	}
	/**
	 * API function , show if the product is new product 
	 */
	public function isNewProductAction(){
		$this->_helper->layout()->disableLayout();
		$sCode = $this->_getParam('barcode');
		$gdata = new Model_DbTable_Apos_Stock_Grndataold(Zend_Registry::get('db_allapos'));
		$result = $gdata->isNewProduct(trim($sCode));
		echo (int)$result;
	}
	
	/**
	 * check if the invoice suit the discount policy
	 */
	public function discountCheckerAction(){
		
		$staff = '';
		$sic = '';
		$mgr = '';
		$des= '<br/> ';
		
		if($_POST){
		$barcode = $_POST['barcode'];
		
		$des = Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/get-old-apos-product-description/barcode/".trim($barcode));
		
		
		$clearCode = (strpos($des,"#C")!==false)?true:false;
		$brandCode = (strpos($des,"#B")!==false)?true:false;
		
		$firstOne = substr(trim($des),0,1);
		$secOne = substr(trim($des),1,1);
		if(($firstOne == 'A' || $firstOne == 'B' || $firstOne == 'C' ) && is_numeric($secOne) && $secOne <6){
			
			switch($firstOne){
				case('A'):{$staff = '10%';$sic = '15%'; $mgr = '20%';break;}
				case('B'):{
					$staff = '20%';$sic = '25%'; $mgr = '30%';break;
				}
				case('C'):{
					$staff = '30%';$sic = '35%'; $mgr = '40%';break;
				}
			}
			
			if($brandCode  && $firstOne == 'C'){
				
				$staff = '30%';$sic = '30%'; $mgr = '30%';
			}
			
		}
		if($clearCode){
			if(!$brandCode){
				$staff = '50%';$sic = '50%'; $mgr = '50%';
			}
			else{
				$staff = '30%';$sic = '30%'; $mgr = '30%';
			}
		}
		
		
		}
		$this->view->disp = array($staff,$sic,$mgr);
		$this->view->des = $des;
	}
	
	/**
	 * regular run on selected day , sometimes when adding new product 
	 * the product do not have price , which need to confirm 
	 * then a list will be send to admin to let them add the price 
	 */
	public function productWithNoPriceAction(){
		
		$pOld = Model_Aposinitnew::initProDes();
		$rows = $pOld->barcodeWithoutPrice();
		$arrRes = array();
		$arrResNew = array();
		if($rows){
			
			foreach($rows as $item){
				// get Current stock
				$stock = Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/get-current-stock/barcode/".$item['SCODE']);
				if($stock){
					if(substr($item['DESCRIPT'],0,2)=='A0'){
						$arrResNew[] = $item;
					}else{
						$arrRes[] = $item;
					}
					
				}	
			}
			
		}
		
		//d($arrRes,$arrResNew);
		$this->view->arrRes = $arrRes;
		$this->view->arrResNew = $arrResNew;
		
		if(count($arrRes) == 0 && count($arrResNew) == 0){
			
			echo "NOEMAILNEEDED";
			
		}
	}
	
	/**
	 * this is the public page to sending the email 
	 */
	public function productWithoutPricePublicAction(){
		
		$content = Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/product-with-no-price");

		if(strpos($content,'NOEMAILNEEDE') === false ){
		$mail = new Model_Emailshandler();
		$mail->sendActionEmail("office@phonecollection.com.au;office5@phonecollection.com.au","The Following Product Still Do Not Have Price", $content);
		}
	}
	
	/**
	 * this is summary report function to give the report of special mode sale s
	 * this function is not in good use 
	 */
	
	public function modelSalesAction(){
		
		set_time_limit(0);
		
		// screening all barcode , 
		$des = Model_Aposinitnew::initProDes();
		$dateBegin = Model_DatetimeHelper::getLastWeekMonday();
		$dateEnd = Model_DatetimeHelper::getLastWeekSunday();
		
		$subType = new Model_DbTable_Barcodeproductsubtype();
		$phoneModel = new Model_DbTable_Barcodemodel();
		$manu = new Model_DbTable_Barcodemanu();
		
		$caseCodeList = $subType->listSubTypeByMainTypeID(1);
		$spCodeList = $subType->listSubTypeByMainTypeID(7);
		

		
		
		$pList = $phoneModel->listAllModel();
		$arrPlist = array();
		$arrCot = array();
		foreach($pList as $k => $v){
			if(trim($v['code_model'])!==''){
				$codeModel = strtoupper(str_replace(' ','',trim($v['code_model'])));
				$idManu = $manu->getManu($v['id_manu_model']);
				$codeModel = $idManu['code_barcode'].$codeModel;
				
				
				$cot = strlen($codeModel);
				if( $cot >1 ){
					$arrCot[] = $cot;
					$arrPlist[] = $codeModel;	
				}
				}
		}
		
		
		$arrCaseList = array();
		
		foreach($caseCodeList as $case){
			$arrCaseList[] = $case['code_sub_type'];
		}		
		$arrSpList = array();
		
		foreach($spCodeList as $sp){
			$arrSpList[] = $sp['code_sub_type'];
		}
		
		
		
		array_multisort($arrCot,SORT_DESC,$arrPlist);
		
		d($arrPlist);
		$barcodeList = $des->getAll();
		$arrModels = array();
		foreach($barcodeList as $item){
			if( strpos($item['SCODE'],'STRAP-') === false && strpos($item['SCODE'],'STA-') === false && is_numeric(trim($item['SCODE'])) == false ){
				$taken = false;
				foreach($arrPlist as $code){
					if(strpos($item['SCODE'],$code)!==false && $taken == false){
						$arrModels[$code][] = $item['SCODE'];
						$taken = true;
					}
				}
				//d($item['SCODE']);
			}
		}
		
		$arrShop = unserialize(ARR_APOS_NEW_SHOP_MAPPING);
		
		d($arrModels);
		
		$arrBarcodes = array();
		
		$cott = 0;
		
		foreach($arrModels as $model => $bList){
			
			//if($model == 'SAI9210' || $model == 'SAN7100' || $model == 'SAI9100' || $model == 'HTCONE' ){
			
			foreach ($bList as $barcode){
				//if($cott < 10000000){
				
			// it is sp
			$salesSp = 0;
			$salesCase = 0;
			$whStock = 0;
			$shopStock = 0;
			
			if(substr($barcode,0,2)=="SP"){
				foreach($arrSpList as $spCode){

					if(strpos($barcode, $spCode)!==false){
						$whStock = Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/get-current-stock/barcode/".trim($barcode));

						foreach($arrShop as $shop => $map){
							$invPro = Model_Aposinitnew::initAposInvPro($shop);
							$salesSp += $invPro->getProductSalesQtyByDates($dateBegin, $dateEnd, $barcode);							
							$shopStock +=  Model_System_Downloadhelper::downloadUrl("http://".SERVER_IP_COMM."/products/get-current-stock/barcode/".trim($barcode)."/shop/".$shop);
						}
						
					}
				}
			}	
			// it is case 	
			foreach($arrCaseList as $caseCode){
				
				if(strpos($barcode, $caseCode)!==false){

						foreach($arrShop as $shop => $map){
							$invPro = Model_Aposinitnew::initAposInvPro($shop);
							$salesCase += $invPro->getProductSalesQtyByDates($dateBegin, $dateEnd, $barcode);							
						}
				}	
			}	

			$arrBarcodes[$model][$barcode]['SP'] = $salesSp;
			$arrBarcodes[$model][$barcode]['CA'] = $salesCase;
			$arrBarcodes[$model][$barcode]['WH'] = $whStock;
			$arrBarcodes[$model][$barcode]['SS'] = $shopStock;
			
				//}
				$cott++;
			}
		//}
		
		}
		d($arrBarcodes);
		$arrRes = array();
		foreach($arrBarcodes as $model => $barcode){
			foreach($barcode as $k => $arr){
				
				
				
				if(isset($arrRes[$model]['SP'])){
				$arrRes[$model]['SP'] += $arr['SP'];
				}
				else{
					$arrRes[$model]['SP'] = $arr['SP'];
				}
				
				if(isset($arrRes[$model]['CA'])){
				$arrRes[$model]['CA'] += $arr['CA'];
				}
				else{
					
					$arrRes[$model]['CA'] = $arr['CA'];
				
				}
				
				
				if(isset($arrRes[$model]['WH'])){
					$arrRes[$model]['WH'] += $arr['WH'];
				}
				else{
						
					$arrRes[$model]['WH'] = $arr['WH'];
				
				}
				
				if(isset($arrRes[$model]['SS'])){
					$arrRes[$model]['SS'] += $arr['SS'];
				}
				else{
				
					$arrRes[$model]['SS'] = $arr['SS'];
				
				}
				
				
				}
				
					$arrRes[$model]['CT'] = count($arrBarcodes[$model]);
					
			
		}
		
		d($arrRes);
		$this->view->arrRes = $arrRes;
	}
	
	/**
	 * this function urn on 126 to active the invoice 
	 */
	public function activeInvoiceShopAction(){
		$shopList = unserialize(ARR_SHOP);
		
		foreach($shopList as $shop){
			
			$inv = Model_Aposinitnew::initAposInvoice($shop);
			$inv->activeInvoice();
		echo $shop."DONE<br />";
		}
	}
	
	/**
	 * API function for product online order 
	 * it gives the result of sale data in apos for public 124 server
	 */
	public function getProductSalesAction(){
		
		$this->_helper->layout()->disableLayout(); 
		
		$params = $this->_getAllParams();
		$invPro = Model_Aposinitnew::initAposInvPro($params['shop']);
		
		$db1W = Model_DatetimeHelper::getLastWeekMonday();
		$dn1W = Model_DatetimeHelper::getLastWeekSunday();
		
		$db2W = Model_DatetimeHelper::adjustWeeks("sub", $db1W, 1);
		$dn2W = Model_DatetimeHelper::adjustWeeks("sub", $dn1W, 1);
		
		if($params['period'] == 'w1'){
			$sales1W = $invPro->getProductSalesQtyByDates($db1W, $dn1W,$params['barcode']);
			echo $sales1W;
		}
		if($params['period'] == 'w2'){
			$sales2W = $invPro->getProductSalesQtyByDates($db2W, $dn2W,$params['barcode']);
			echo $sales2W;
		}
		if($params['period'] == 'max'){
			$maxSold = $invPro->maxSoldWeeks($params['barcode'], $dn1W,4);
			echo $maxSold;
		}
	}
	
	public function getProductListAction(){
		
		
		$this->_helper->layout()->disableLayout();
		$shop = $this->_getParam("shop");
		
		$invPro = Model_Aposinitnew::initAposInvPro($shop);
		$stockWh = Model_Aposinitnew::initProBalanceAll();
		$stockShop = Model_Aposinitnew::initProStock($shop);
		$pd = Model_Aposinitnew::initProDes();
		$weeklyOrder = new Model_DbTable_Order_Weeklyorder(Zend_Registry::get('db_remoteapp'));
		$orderCate = new Model_Products_Categoryorder(Zend_Registry::get('db_remoteapp'));
		$pro = new Model_DbTable_Productsva(Zend_Registry::get('db_remoteapp'));
		$thisMonday = Model_DatetimeHelper::getThisWeekMonday("");
		$noOrder = "PD".$shop.$thisMonday;
		
		if($shop == 'CLIC'){
			$shop = 'CLPC';
		}
		
		$cList = $stockWh->listStockWhHave();
		$sList = $stockShop->listShopEmpty($shop);
		$oList = $weeklyOrder->getOrderByNo($noOrder);
		
		
		$whList = array();
		foreach ($cList as $k => $v){
			$sCode = trim($v['SCODE']);
			if(!in_array($sCode,self::$arrbarCodeFilter) && strpos($sCode,"STRAP-") === false){
				if((int)$v['BALANCE'] > 0){
					$whList[$sCode] = (int)$v['BALANCE'];
				}
			}
		}
		
		
		$sNoStock = array(); 	//Shop no stock item
		foreach ($sList as $k2 => $v2){
			$sCode = trim($v2['SCODE']);
			if(!in_array($sCode,self::$arrbarCodeFilter) && strpos($sCode,"STRAP-") === false){
				$sNoStock[$sCode] = 0;
			}
		}
		$shopOrder = array(); 	//Shop order qty > 0 list
		foreach ($oList as $k3 => $v3){
				$shopOrder[$v3['code_product']] = $v3['qty_order_shop'];		
		}
		
		$list = array();
		foreach ($cList as $k => $v){
			$sCode = trim($v['SCODE']);
			if(!in_array($sCode,self::$arrbarCodeFilter) && strpos($sCode,"STRAP-") === false){
				if(array_key_exists($sCode, $sNoStock) && !array_key_exists($sCode, $shopOrder)){
						
					$desProductLine =$pd->getAposDes($sCode);
					$list[$sCode] = $v;
					$list[$sCode]['code_product'] = $sCode;
					$list[$sCode]['DESCRIPT'] = $desProductLine['DESCRIPT'];
				}
		
			}
		}
		foreach ($list as $code => $detail){
			echo $code .",".$detail['DESCRIPT'].";";
		}
		
	}
	
	/**
	 * API function  for product online order
	 * it gives if he item for this shop is HOT or not 
	 */
	public function  isHotProductAction(){
		
		$this->_helper->layout()->disableLayout();
		
		$params = $this->_getAllParams();
		$invPro = Model_Aposinitnew::initAposInvPro($params['shop']);

		echo $invPro->isHotItem($params['barcode']);

	}
	
	/**
	 * API function for product onine order
	 * according the given number 
	 * it gives the order qty 
	 */
	public function orderQtyAction(){
		$this->_helper->layout()->disableLayout();
		
		$params = $this->_getAllParams();
		$invPro = Model_Aposinitnew::initAposInvPro($params['shop']);
		$orderQty = $invPro->calOrderQty($params['w1'],$params['w2'],$params['sk_shop'],$params['is_hot'],$params['max'],$params['is_new'],$params['is_sp']);
		
		echo $orderQty;
	}
	
	/**
	 * This is the function for product online order 
	 * it format the order in different category array
	 * 
	 * @param unknown_type $arrOrderList
	 * @return Ambigous <multitype:, unknown>
	 */
	public function formatOrderByCategory($arrOrderList){
		
		$cMappping = new Model_Products_Catemapping();
		$product = new Model_DbTable_Productsva();
		
		$arrRes = array();
		foreach($arrOrderList as $k => $v){
			
			$codeProduct = $v['code_product'];
			$pInfo = $product->getProductByBarcode($codeProduct);
			
			//d($codeProduct,$arrCategory);
			if($pInfo){
				
				$idCategory = $cMappping->getOrderCategory($pInfo['cat1'],$pInfo['cat2']);
				if(!$idCategory){
					$idCategory = 19;
				}
					$arrRes[$idCategory][] = $v;
			}else{
				$idCategory = 19;
				$arrRes[$idCategory][] = $v;
			}
			
			
			
		}
		ksort($arrRes);
		return $arrRes;
	}
	/**
	 * API Ajax function 
	 * when order Qty updated it gives success or fail 
	 */
	public function serviceUpdateWeeklyOrderQtyAction(){
		
		$this->_helper->layout()->disableLayout();
		
		$idOrder = $this->_getParam("id_order");
		$orderQtyShop = $this->_getParam("qty_order");
		
		$wOrder = new Model_DbTable_Order_Weeklyorder();
		
		if(is_numeric($idOrder) && is_numeric($orderQtyShop)){
			
			$wOrder->reviseQtyShop($idOrder, $orderQtyShop);
		
			echo "SUCCESS";
		}else{
			echo "FAIL";
		}
		
	}
}
?>